diff --git a/Cargo.lock b/Cargo.lock index 49ca15068f..6f525f7c14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -919,6 +919,11 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-cfb" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" + [[package]] name = "craft-cfb" version = "0.1.0" @@ -932,12 +937,23 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", + "kurbo", + "log", + "serde", +] + [[package]] name = "craft-drawingml" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", "kurbo", "log", "serde", @@ -981,6 +997,44 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-math" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "serde", +] + +[[package]] +name = "craft-odf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "aes", + "base64 0.23.1", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "flate2", + "getrandom 0.3.4", + "hmac", + "sha1 0.11.0", + "sha2 0.11.1", + "thiserror 2.0.21", + "zeroize", +] + +[[package]] +name = "craft-ods" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "craft-odf", + "craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "thiserror 2.0.21", +] + [[package]] name = "craft-offcrypto" version = "0.1.0" @@ -988,8 +1042,8 @@ source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d dependencies = [ "aes", "base64 0.23.1", - "craft-cfb", - "craft-xml", + "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", "getrandom 0.3.4", "hmac", "sha1 0.11.0", @@ -1003,8 +1057,8 @@ name = "craft-opc" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ - "craft-xml", - "craft-zip", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", "log", "thiserror 2.0.21", ] @@ -1028,6 +1082,16 @@ dependencies = [ "winsafe", ] +[[package]] +name = "craft-sheet" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" + +[[package]] +name = "craft-sheet" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" + [[package]] name = "craft-sheet" version = "0.1.0" @@ -1133,10 +1197,10 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" dependencies = [ - "craft-cfb", - "craft-sheet", + "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", + "craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", "md-5", "miniz_oxide 0.9.1", "sha1 0.10.7", @@ -1148,10 +1212,30 @@ name = "craft-xlsx" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ - "craft-drawingml", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", "craft-opc", - "craft-sheet", - "craft-xml", + "craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" +dependencies = [ + "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] @@ -1164,6 +1248,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.0", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -2403,13 +2497,16 @@ dependencies = [ name = "gridcraft-xlsx" version = "0.19.1" dependencies = [ - "craft-cfb", + "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", "craft-csv", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e)", + "craft-math", + "craft-ods", "craft-offcrypto", "craft-opc", "craft-xls", "craft-xlsx", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", "gridcraft-core", "gridcraft-formula", "gridcraft-functions", diff --git a/Cargo.toml b/Cargo.toml index 8011136db0..e6e2727072 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,18 +37,21 @@ craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = " # Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]). craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" } # OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`. craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } # Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs` # turn them into workbooks. craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" } # The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back. craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. # SpreadsheetML string encoding/decoding; workbook model mapping stays in gridcraft-xlsx. craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "3b8e426a260695af840a2cd79a064d40778f939e", version = "0.1.0" } # foundation thiserror = "2" diff --git a/ROADMAP.md b/ROADMAP.md index c4ac8517ec..6df4e6c941 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365) > **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-11-16 | A selected chart outlines its data as Excel does (series names red, category labels purple, values one blue block), and dragging a corner of the values outline changes the cells the chart plots: series keep their formatting, a wider block adds series, aligned names and labels follow, one undo step, Esc cancels; `chart.setValuesRange` does the same for scripts, the CLI and MCP (#4389, #4390) | | 2026-11-06 | A sheet keeps its own scroll position when sheets are inserted, deleted or moved before it: a new PivotTable or inserted sheet opens at the top instead of where its neighbour was scrolled; a closed window's positions are let go (#3485) | | 2026-11-02 | Form controls: Insert › Controls places buttons, sliders (scroll bars) and spin buttons on the sheet. A slider or spin button holds a whole number from 0 to 30000 in a linked cell (a drag or a held arrow is one undo step, and editing the cell moves the control); a button runs a macro or one command through the macro policy, asking first in a workbook opened from a file; Assign Action and Format Control edit them, and XLSX files read and write them (control properties, `` and VML), alongside the form controls GridCraft keeps unchanged | | 2026-11-02 | Dialogs take ranges by selection on the grid: reference boxes (RefEdit) with a collapse button that shrinks the dialog while the person selects, in Goal Seek, Solver (including the Model Range of Load/Save) and Data Analysis; while collapsed, the arrow keys move the selection and Shift+arrow extends it, and F4 cycles a reference's anchors | @@ -187,6 +188,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) | | 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) | | 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison | +| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate | | 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift | | 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) | | 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles | @@ -277,6 +279,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) | | 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) | | 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update | | 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row | @@ -321,6 +324,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row | | 2026-10-14 | minor | Progress log: spill anchor reading its old spill area | | 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict | +| 2026-10-14 | trivial | Progress log: RATE follows Excel's iteration | | 2026-10-13 | trivial | Progress log: More Colors… and Recent Colors in the colour menus (#928) | | 2026-10-13 | minor | Multi-level category axes (read, drawn, written); progress log row | | 2026-10-13 | trivial | Progress log: shared pictures written once on XLSX export (#985) | diff --git a/crates/engine/src/cf.rs b/crates/engine/src/cf.rs index c49dffccdd..8129c52f84 100644 --- a/crates/engine/src/cf.rs +++ b/crates/engine/src/cf.rs @@ -737,6 +737,43 @@ mod tests { assert_eq!([look("A1"), look("A2")], [true, false]); } + #[test] + fn rules_compare_with_cells_on_other_sheets() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "E1", "values": [["Suspended"], ["OK"], ["Terminated"], [7], [3]]})).unwrap(); + let rule = |r: serde_json::Value| json!({"range": "E1:E5", "rule": r}); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$8", "preset": "redText"})), + ) + .unwrap(); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$9", "preset": "redText"})), + ) + .unwrap(); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "expression", "formula": "=AND(ISNUMBER(E1),E1>'Vehicle Range'!$B$1)", "preset": "yellowFill"})), + ) + .unwrap(); + s.execute("home.insertSheet", json!({"name": "Vehicle Range"})).unwrap(); + s.execute("range.setValues", json!({"range": "'Vehicle Range'!A8", "values": [["Suspended"], ["Terminated"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "'Vehicle Range'!B1", "values": [[5]]})).unwrap(); + let d = s.doc().unwrap(); + let report = d.wb.sheets.iter().position(|sh| sh.name != "Vehicle Range").unwrap(); + let mut cache = CfCache::new(); + let mut look = |a: &str| cache.look(&d.wb, report, CellRef::parse(a).unwrap()).and_then(|l| l.style).unwrap_or_default(); + let looks = ["E1", "E2", "E3", "E4", "E5"].map(&mut look); + // The cells equal to 'Vehicle Range'!A8 or A9 get the red text. + let red_text = looks[0].font.color; + assert_ne!(red_text, Color::Auto); + let red = |st: &Style| st.font.color == red_text; + let filled = |st: &Style| st.fill.pattern == PatternType::Solid; + assert_eq!(looks.each_ref().map(red), [true, false, true, false, false]); + assert_eq!(looks.each_ref().map(filled), [false, false, false, true, false]); + } #[test] fn text_rules_skip_error_values() { let mut s = crate::Session::new(); diff --git a/crates/engine/src/chart_data.rs b/crates/engine/src/chart_data.rs new file mode 100644 index 0000000000..47bcef2fe4 --- /dev/null +++ b/crates/engine/src/chart_data.rs @@ -0,0 +1,213 @@ +//! Where a chart's data sits on a sheet, as the blocks a selected chart outlines: series names in +//! red, category labels in purple and values in blue (#4390). Dragging a corner of the values +//! block points the chart at other cells, and the names and categories follow it (#4389). + +use gridcraft_core::{CellRef, RangeRef, col_to_letters}; +use gridcraft_formula::{Expr, RefKind, SheetSel, parse, quote_sheet}; +use gridcraft_model::{Chart, Series, Workbook}; + +/// Most series a chart takes from a dragged block (Excel's limit per chart). +pub const MAX_SERIES: u32 = 255; +/// Most cells a dragged values block may span, as for `chart.selectData`. +pub const MAX_CELLS: u64 = 1_000_000; + +/// A chart's data as blocks of cells on one sheet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChartData { + /// The sheet the data is on. + pub sheet: usize, + /// Every series' values: one column per series (one row with `by_rows`), in series order. + pub values: RangeRef, + /// Series run across rows rather than down columns. + pub by_rows: bool, + /// The category labels every series shares, when they line up beside `values`. + pub categories: Option, + /// One name cell per series, in the line beside `values`, when every series has one there. + pub names: Option, +} + +impl ChartData { + /// The blocks after the values move to `to`: category labels keep their column (row) and + /// span the new points, and names keep their row (column) and span the new series. + pub fn moved(&self, to: RangeRef) -> ChartData { + let (categories, names) = if self.by_rows { + ( + self.categories.map(|c| RangeRef::new(CellRef::new(c.start.row, to.start.col), CellRef::new(c.start.row, to.end.col))), + self.names.map(|n| RangeRef::new(CellRef::new(to.start.row, n.start.col), CellRef::new(to.end.row, n.start.col))), + ) + } else { + ( + self.categories.map(|c| RangeRef::new(CellRef::new(to.start.row, c.start.col), CellRef::new(to.end.row, c.start.col))), + self.names.map(|n| RangeRef::new(CellRef::new(n.start.row, to.start.col), CellRef::new(n.start.row, to.end.col))), + ) + }; + ChartData { values: to, categories, names, ..*self } + } + + /// The cells of series `i` within `values` (`None` past the last series). + fn line(&self, values: RangeRef, i: u32) -> Option { + if self.by_rows { + let row = values.start.row.checked_add(i).filter(|r| *r <= values.end.row)?; + Some(RangeRef::new(CellRef::new(row, values.start.col), CellRef::new(row, values.end.col))) + } else { + let col = values.start.col.checked_add(i).filter(|c| *c <= values.end.col)?; + Some(RangeRef::new(CellRef::new(values.start.row, col), CellRef::new(values.end.row, col))) + } + } + + /// How many series `values` holds. + fn count(&self, values: RangeRef) -> u32 { + if self.by_rows { values.height() } else { values.width() } + } +} + +/// The sheet and cells a series reference names. `home` is the chart's own sheet, for an +/// unqualified reference. Literals, names, 3-D spans, other workbooks and whole rows or columns +/// are not blocks. +fn block(wb: &Workbook, home: usize, text: &str) -> Option<(usize, RangeRef)> { + let Ok(Expr::Ref(r)) = parse(text.trim().trim_start_matches('=')) else { return None }; + let sheet = match &r.sheet { + SheetSel::Current => home, + SheetSel::Named(n) => wb.sheet_index(n)?, + SheetSel::Span(..) => return None, + }; + matches!(r.kind, RefKind::Cell(_) | RefKind::Range(..)).then(|| (sheet, r.range())) +} + +/// `chart`'s data on `home`'s workbook as blocks, when its series form one: every series' values +/// on one sheet, in adjacent columns (or rows) of the same extent, in series order. `None` for +/// any other layout, and for a PivotChart, whose series follow its PivotTable. +pub fn chart_data(wb: &Workbook, home: usize, chart: &Chart) -> Option { + if chart.pivot.is_some() { + return None; + } + let first = chart.series.first()?; + let (sheet, r0) = block(wb, home, &first.values)?; + let by_rows = match (r0.width(), r0.height()) { + (1, 1) => chart.by_rows, + (1, _) => false, + (_, 1) => true, + _ => return None, + }; + let n = u32::try_from(chart.series.len()).ok()?; + let last = n.checked_sub(1)?; + let values = if by_rows { + RangeRef::new(r0.start, CellRef::new(r0.end.row.checked_add(last)?, r0.end.col)) + } else { + RangeRef::new(r0.start, CellRef::new(r0.end.row, r0.end.col.checked_add(last)?)) + }; + let mut data = ChartData { sheet, values, by_rows, categories: None, names: None }; + for (i, se) in (0..n).zip(&chart.series) { + if block(wb, home, &se.values) != Some((sheet, data.line(values, i)?)) { + return None; + } + } + // Category labels shared by every series, in one line beside the points. Compared as blocks, + // not text: `=Sheet1!$A$2:$A$4` and `Sheet1!$A$2:$A$4` are the same labels. + let cats = |se: &Series| se.categories.as_deref().and_then(|t| block(wb, home, t)); + if let Some((s, c)) = cats(first) + && s == sheet + && chart.series.iter().all(|se| cats(se) == Some((s, c))) + { + let lines_up = if by_rows { + c.height() == 1 + && (c.start.col, c.end.col) == (values.start.col, values.end.col) + && !(values.start.row..=values.end.row).contains(&c.start.row) + } else { + c.width() == 1 + && (c.start.row, c.end.row) == (values.start.row, values.end.row) + && !(values.start.col..=values.end.col).contains(&c.start.col) + }; + data.categories = lines_up.then_some(c); + } + // A name cell for every series, all in one line beside the values. + let names: Option> = chart + .series + .iter() + .map(|se| se.name.as_deref().and_then(|t| block(wb, home, t)).filter(|(s, r)| *s == sheet && r.is_single()).map(|(_, r)| r.start)) + .collect(); + if let Some(cells) = names + && let (Some(a), Some(b)) = (cells.first(), cells.last()) + { + let lines_up = (0..n).zip(&cells).all(|(i, c)| { + if by_rows { + c.col == a.col && Some(c.row) == values.start.row.checked_add(i) && !(values.start.col..=values.end.col).contains(&c.col) + } else { + c.row == a.row && Some(c.col) == values.start.col.checked_add(i) && !(values.start.row..=values.end.row).contains(&c.row) + } + }); + data.names = lines_up.then(|| RangeRef::new(*a, *b)); + } + Some(data) +} + +/// Why [`with_values`] refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ValuesError { + /// The chart's series are not one block of cells ([`chart_data`] is `None`). + NotABlock, + /// The block is over [`MAX_CELLS`] cells or [`MAX_SERIES`] series. + TooLarge, +} + +/// `chart` with its values moved to `to` on the data's own sheet, as dragging a corner of the +/// values outline does. Series `i` takes the `i`-th column (row) of `to` and keeps everything +/// else it had (colour, kind, axis, trendlines); a wider block adds series and a narrower one +/// drops the last ones. Category labels and names that line up follow the block; ones that don't +/// stay as they are. A data range kept for Switch Row/Column becomes the moved blocks. +pub fn with_values(wb: &Workbook, home: usize, chart: &Chart, to: RangeRef) -> Result { + let data = chart_data(wb, home, chart).ok_or(ValuesError::NotABlock)?; + if to.count() > MAX_CELLS || data.count(to) > MAX_SERIES { + return Err(ValuesError::TooLarge); + } + let sheet = wb.sheet(data.sheet).ok_or(ValuesError::NotABlock)?; + let q = quote_sheet(&sheet.name); + let row = |r: u32| u64::from(r) + 1; + let range = |r: RangeRef| format!("{q}!${}${}:${}${}", col_to_letters(r.start.col), row(r.start.row), col_to_letters(r.end.col), row(r.end.row)); + let cell = |c: CellRef| format!("{q}!${}${}", col_to_letters(c.col), row(c.row)); + let moved = data.moved(to); + let shared_cats = chart.series.first().and_then(|se| se.categories.clone()); + let mut out = chart.clone(); + // Keep the orientation the series were read in: a block of one cell per series is read by + // `by_rows`, so a stale flag would make the moved series unreadable as a block. + out.by_rows = data.by_rows; + out.series = (0..data.count(to)) + .filter_map(|i| { + let line = moved.line(to, i)?; + let old = chart.series.get(i as usize); + let mut se = old.cloned().unwrap_or_else(|| Series { categories: shared_cats.clone(), ..Series::default() }); + se.values = range(line); + if let Some(c) = moved.categories { + se.categories = Some(range(c)); + } + if let Some(n) = moved.names { + se.name = + Some(cell(if data.by_rows { CellRef::new(line.start.row, n.start.col) } else { CellRef::new(n.start.row, line.start.col) })); + } + // Bubble sizes in a line of their own beside the old points span the new ones. + if let (Some(old_line), Some(text)) = (data.line(data.values, i), se.bubble_sizes.clone()) + && let Some((s, b)) = block(wb, home, &text) + && s == data.sheet + { + let follows = if data.by_rows { + b.height() == 1 && (b.start.col, b.end.col) == (old_line.start.col, old_line.end.col) + } else { + b.width() == 1 && (b.start.row, b.end.row) == (old_line.start.row, old_line.end.row) + }; + if follows { + se.bubble_sizes = Some(range(if data.by_rows { + RangeRef::new(CellRef::new(b.start.row, to.start.col), CellRef::new(b.start.row, to.end.col)) + } else { + RangeRef::new(CellRef::new(to.start.row, b.start.col), CellRef::new(to.end.row, b.start.col)) + })); + } + } + Some(se) + }) + .collect(); + if out.source.is_some() { + let all = [moved.categories, moved.names].into_iter().flatten().fold(to, |a, r| a.union(&r)); + out.source = Some(format!("{q}!{}", all.a1())); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index c8921718c2..bea9475c1c 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -96,6 +96,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result { line: Color::from_hex(&color).unwrap_or(Color::rgb(0x1F, 0x5F, 0xC9)), text, format: Default::default(), + rotation: 0.0, }; edit(s, |cx| { cx.sheet_mut(si)?.shapes.push(shape); diff --git a/crates/engine/src/cmd/equation.rs b/crates/engine/src/cmd/equation.rs index d485a3535c..0d6bc732c7 100644 --- a/crates/engine/src/cmd/equation.rs +++ b/crates/engine/src/cmd/equation.rs @@ -95,6 +95,7 @@ fn insert_equation(s: &mut Session, p: &Json) -> Result { text: latex.to_string(), format: Default::default(), math: Default::default(), + rotation: 0.0, }; shape.math.refresh(latex); let sheet = d.wb.active_sheet(); diff --git a/crates/engine/src/cmd/extra.rs b/crates/engine/src/cmd/extra.rs index 6325de45ae..47526bf4af 100644 --- a/crates/engine/src/cmd/extra.rs +++ b/crates/engine/src/cmd/extra.rs @@ -22,7 +22,7 @@ mod window; pub(crate) use cells::is_checkbox_cell; use cells::{background, checkbox, draw_border, new_cell_style, recently_used, theme_colors, theme_fonts, toggle_checkbox, use_in_formula}; -use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data}; +use chart::{add_element, change_colors, format_series, move_chart, quick_layout, select_data, set_values_range}; use data::{from_csv, from_table_range, queries, table_resize}; use objects::{align, arrange, rotate, selection_pane, shape_fill, shape_outline}; pub(crate) use scripts::has_scripts; @@ -61,6 +61,16 @@ pub fn specs() -> Vec { has_doc, select_data ), + // Dragging a corner of a selected chart's values outline on the sheet (#4389). + cmd!( + "chart.setValuesRange", + "Resize Chart Data", + [], + None, + "{chart?, range: \"B2:C9\" (the block every series' values come from, one column or row per series, on the data's sheet; names and category labels that line up follow it, series keep their formatting)}", + has_doc, + set_values_range + ), cmd!("chart.changeType", "Change Chart Type…", ["Chart Design", "Type"], None, "{chart?, type, subtype?}", has_doc, |s, p| s .execute("chart.set", p.clone())), cmd!( diff --git a/crates/engine/src/cmd/extra/chart.rs b/crates/engine/src/cmd/extra/chart.rs index 8d9af2064d..b6ed184edf 100644 --- a/crates/engine/src/cmd/extra/chart.rs +++ b/crates/engine/src/cmd/extra/chart.rs @@ -233,6 +233,38 @@ pub(super) fn select_data(s: &mut Session, p: &Json) -> Result { }) } +/// Points the chart's series at another block of cells on their sheet, keeping each series' +/// formatting, as dragging a corner of the selected chart's values outline does (#4389). +pub(super) fn set_values_range(s: &mut Session, p: &Json) -> Result { + use crate::chart_data::{ValuesError, chart_data, with_values}; + let text = str_param(p, "range").ok_or_else(|| bad("chart.setValuesRange", "missing `range`"))?; + let (si, ci) = find_chart(s, p)?; + let d = s.doc()?; + let chart = d.wb.sheet(si).and_then(|sh| sh.charts.get(ci)).ok_or_else(|| bad("chart", "no such chart"))?; + let Some(data) = chart_data(&d.wb, si, chart) else { + return Err(bad("chart.setValuesRange", "the chart's series are not one block of cells")); + }; + let (sheet_name, body) = split_sheet(text.trim().trim_start_matches('=')); + if let Some(n) = sheet_name + && d.wb.sheet_index(&n) != Some(data.sheet) + { + return Err(bad("chart.setValuesRange", "the range must be on the sheet the chart's data is on")); + } + let to = RangeRef::parse(body).ok_or_else(|| bad("chart.setValuesRange", "not a range"))?; + let new = with_values(&d.wb, si, chart, to).map_err(|e| match e { + ValuesError::NotABlock => bad("chart.setValuesRange", "the chart's series are not one block of cells"), + ValuesError::TooLarge => bad("chart.setValuesRange", "range too large for a chart"), + })?; + let values = format!("{}!{}", gridcraft_formula::quote_sheet(d.wb.sheet(data.sheet).map_or("", |sh| sh.name.as_str())), to.a1()); + with_chart(s, p, move |c| { + c.series = new.series; + c.source = new.source; + c.by_rows = new.by_rows; + Ok(()) + }) + .map(|r| json!({"chart": r["chart"], "values": values})) +} + pub(super) fn move_chart(s: &mut Session, p: &Json) -> Result { let (si, ci) = find_chart(s, p)?; let target = match p.get("sheet").and_then(Json::as_str) { diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index 0cef545672..686fca6f5c 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -164,7 +164,7 @@ pub fn specs() -> Vec { "Move Object", [], None, - "{kind: chart|image|shape|slicer|equation|control, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger)}", + "{kind: chart|image|shape|slicer|equation|control, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger), rotation?: degrees clockwise (shapes, not ink)}", has_doc, move_object ), diff --git a/crates/engine/src/cmd/insert/cond_format.rs b/crates/engine/src/cmd/insert/cond_format.rs index e175974db3..0ce4bbf2c1 100644 --- a/crates/engine/src/cmd/insert/cond_format.rs +++ b/crates/engine/src/cmd/insert/cond_format.rs @@ -358,6 +358,7 @@ pub(super) fn insert_icon(s: &mut Session, p: &Json) -> Result { line: Color::Auto, text: name, format: Default::default(), + rotation: 0.0, math: Default::default(), }; let sheet = d.wb.active_sheet(); diff --git a/crates/engine/src/cmd/insert/objects.rs b/crates/engine/src/cmd/insert/objects.rs index 22a0575d29..4079d7f2af 100644 --- a/crates/engine/src/cmd/insert/objects.rs +++ b/crates/engine/src/cmd/insert/objects.rs @@ -163,6 +163,7 @@ pub(super) fn insert_shape(s: &mut Session, p: &Json) -> Result { line, text: str_param(p, "text").unwrap_or("").into(), format: Default::default(), + rotation: 0.0, math: Default::default(), }; let sheet = d.wb.active_sheet(); @@ -237,6 +238,16 @@ pub(super) fn delete_object(s: &mut Session, p: &Json) -> Result { pub(super) fn move_object(s: &mut Session, p: &Json) -> Result { let (sheet, o) = object_param(s, p, "object.move")?; let at = cell_param(s, p, "at")?; + let rotation = f64_param(p, "rotation").filter(|v| v.is_finite()); + if rotation.is_some() { + let ink = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.shapes.iter().any(|x| x.id == o.id && x.kind == ShapeKind::Ink)); + if o.kind != ObjKind::Shape || ink { + return Err(bad("object.move", "only shapes other than ink rotate")); + } + if s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.is_protected()) { + return Err(EngineError::Other(PROTECTED.into())); + } + } edit(s, |cx| { let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.move", "no such object")) }; if let Some(at) = at { @@ -254,6 +265,11 @@ pub(super) fn move_object(s: &mut Session, p: &Json) -> Result { if let Some(v) = f64_param(p, "height") { a.height = v.clamp(0.0, size_cap(a.height)) as f32; } + if let Some(r) = rotation + && let Some(shape) = cx.sheet_mut(sheet)?.shapes.iter_mut().find(|x| x.id == o.id) + { + shape.rotation = r.rem_euclid(360.0) as f32; + } Ok(Json::Null) }) } diff --git a/crates/engine/src/cmd/print/objects.rs b/crates/engine/src/cmd/print/objects.rs index 1def11bf53..ddd9300a2c 100644 --- a/crates/engine/src/cmd/print/objects.rs +++ b/crates/engine/src/cmd/print/objects.rs @@ -1,6 +1,6 @@ use super::draw::{Block, PdfMeasure, Xf, draw_prims, rgb_of}; use super::text::wrap_lines; -use super::{Anchor, CellRef, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook}; +use super::{Anchor, Baseline, CellRef, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook}; use std::borrow::Cow; use std::collections::hash_map::Entry; @@ -269,29 +269,42 @@ fn draw_sparklines(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Bloc fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Block, (x, y, w, h): (f32, f32, f32, f32)) { let fill = rgb_of(shp.fill, wb); let line = rgb_of(shp.line, wb).filter(|_| !shp.format.no_line).map(|c| (c, (0.75 * b.k).max(0.25))); + let angle = if shp.rotation.is_finite() { shp.rotation.to_radians() } else { 0.0 }; + let (sn, cs) = angle.sin_cos(); + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + let turn = |[px, py]: [f32; 2]| { + let (dx, dy) = (px - cx, py - cy); + [cx + dx * cs - dy * sn, cy + dx * sn + dy * cs] + }; match shp.kind { ShapeKind::Ellipse => { let pts: Vec<[f32; 2]> = (0..72) .map(|i| { let a = i as f32 / 72.0 * std::f32::consts::TAU; - [x + w / 2.0 + w / 2.0 * a.cos(), y + h / 2.0 + h / 2.0 * a.sin()] + turn([x + w / 2.0 + w / 2.0 * a.cos(), y + h / 2.0 + h / 2.0 * a.sin()]) }) .collect(); pg.polygon(&pts, fill, line); } - ShapeKind::Triangle => pg.polygon(&[[x + w / 2.0, y], [x + w, y + h], [x, y + h]], fill, line), + ShapeKind::Triangle => { + let pts = [[x + w / 2.0, y], [x + w, y + h], [x, y + h]].map(turn); + pg.polygon(&pts, fill, line); + } ShapeKind::Line | ShapeKind::Arrow => { let c = line.map(|l| l.0).or(fill).unwrap_or([0, 0, 0]); - pg.stroke_line(x, y, x + w, y + h, (1.0 * b.k).max(0.3), c); + let [x0, y0] = turn([x, y]); + let [x1, y1] = turn([x + w, y + h]); + pg.stroke_line(x0, y0, x1, y1, (1.0 * b.k).max(0.3), c); if shp.kind == ShapeKind::Arrow { let ang = h.atan2(w); let al = 8.0 * b.k; - let p = |da: f32| [x + w - al * (ang + da).cos(), y + h - al * (ang + da).sin()]; - pg.polygon(&[[x + w, y + h], p(0.4), p(-0.4)], Some(c), None); + let p = |da: f32| turn([x + w - al * (ang + da).cos(), y + h - al * (ang + da).sin()]); + pg.polygon(&[turn([x + w, y + h]), p(0.4), p(-0.4)], Some(c), None); } } _ => { - pg.polygon(&[[x, y], [x + w, y], [x + w, y + h], [x, y + h]], fill, line); + let pts = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(turn); + pg.polygon(&pts, fill, line); } } if shp.text.is_empty() { @@ -322,7 +335,8 @@ fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Bl // WordArt's drop shadow: the line again, offset, in the shadow colour (under the text). if let Some(sc) = fm.text_shadow.and_then(|c| rgb_of(c, wb)) { let off = (size * 0.06).max(0.5); - pg.text_with_direction(Point::new(lx + off, yy + off), size, font, sc, &l.text, l.direction); + let [sx, sy] = turn([lx + off, yy + off]); + pg.text_rotated_with_direction(Baseline { origin: Point::new(sx, sy), angle }, size, font, sc, &l.text, l.direction); } // WordArt's text outline, as on screen: the line in the outline colour, offset in eight // directions by half the outline width, under the filled text. @@ -331,10 +345,12 @@ fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Bl { let d = (ow * b.scale / 2.0).clamp(0.25, 20.0); for (dx, dy) in [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)] { - pg.text_with_direction(Point::new(lx + dx * d, yy + dy * d), size, font, oc, &l.text, l.direction); + let [ox, oy] = turn([lx + dx * d, yy + dy * d]); + pg.text_rotated_with_direction(Baseline { origin: Point::new(ox, oy), angle }, size, font, oc, &l.text, l.direction); } } - pg.text_with_direction(Point::new(lx, yy), size, font, color, &l.text, l.direction); + let [tx, ty] = turn([lx, yy]); + pg.text_rotated_with_direction(Baseline { origin: Point::new(tx, ty), angle }, size, font, color, &l.text, l.direction); yy += size * 1.2; } } diff --git a/crates/engine/src/cmd/print/tests.rs b/crates/engine/src/cmd/print/tests.rs index f6d90f70c1..853e59937d 100644 --- a/crates/engine/src/cmd/print/tests.rs +++ b/crates/engine/src/cmd/print/tests.rs @@ -88,6 +88,34 @@ fn pdf_export_keeps_safe_links_on_their_printed_pages() { assert!(!cropped.contains("/Dest [")); } +#[test] +fn pdf_export_rotates_a_shape_outline_and_its_text() { + let make_page = |rotation| { + let mut s = s(); + let id = s + .execute( + "insert.shape", + json!({"kind": "rectangle", "at": "A1", "width": 120, "height": 60, "text": "TURNED", "fill": "#FF0000", "line": "#0000FF"}), + ) + .unwrap()["shape"] + .as_u64() + .unwrap(); + if rotation != 0 { + s.execute("object.move", json!({"kind": "shape", "id": id, "at": "A1", "rotation": rotation})).unwrap(); + } + pdf_pages(&mut s).remove(0) + }; + let upright = make_page(0); + let turned = make_page(90); + let red_path = |page: &str| { + let start = page.find("1 0 0 rg").expect("red rectangle fill"); + let tail = &page[start..]; + let end = tail.find(" B").expect("filled and stroked rectangle path") + 2; + tail[..end].to_string() + }; + assert_ne!(red_path(&upright), red_path(&turned), "the rectangle's printed outline is rotated"); + assert!(turned.contains("0 -1 1 0") && turned.contains("(TURNED) Tj"), "shape text uses the rotation matrix: {turned}"); +} #[test] fn arabic_with_characters_its_font_lacks_still_exports() { let mut s = s(); diff --git a/crates/engine/src/cmd/wordart.rs b/crates/engine/src/cmd/wordart.rs index 3577591a6a..81171fe918 100644 --- a/crates/engine/src/cmd/wordart.rs +++ b/crates/engine/src/cmd/wordart.rs @@ -194,6 +194,7 @@ fn insert_word_art(s: &mut Session, p: &Json) -> Result { text: text.clone(), format: ShapeFormat { no_line: true, align: Some(ShapeTextAlign::Center), anchor: Some(ShapeTextAnchor::Middle), ..Default::default() }, math: Default::default(), + rotation: 0.0, }; apply("insert.wordArt", &mut shape, Some(style), p)?; // Default box: the longest line at the font size (about 0.62 em per character) plus padding. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 99fb64efd5..d33a020b6a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ pub mod catalog; pub mod cf; +pub mod chart_data; mod chart_svg; mod clip_html; pub mod cmd; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd699bf1c6..ae5f15d171 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5790,6 +5790,56 @@ fn filtered_copy_with_many_runs_moves_notes_and_merges_with_their_rows() { assert_eq!(sh.merges.iter().filter(|m| m.start.col >= 7).count(), 1); } +#[test] +fn object_move_refuses_to_rotate_ink() { + let mut s = s(); + let id = s.execute("draw.stroke", json!({"points": [[0, 0], [30, 20], [60, 5]]})).unwrap()["shape"].clone(); + assert!(s.execute("object.move", json!({"kind": "shape", "id": id, "rotation": 45})).is_err()); + assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 0.0); +} + +#[test] +fn object_move_rotates_shapes_only() { + let mut s = s(); + let id = s.execute("insert.shape", json!({"kind": "rectangle"})).unwrap()["shape"].clone(); + s.execute("object.move", json!({"kind": "shape", "id": id, "rotation": -30})).unwrap(); + assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 330.0); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 0.0); + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + let chart = s.execute("insert.chart", json!({"type": "column"})).unwrap()["chart"].clone(); + assert!(s.execute("object.move", json!({"kind": "chart", "id": chart, "rotation": 45})).is_err()); +} + +#[test] +fn object_move_rotation_respects_sheet_protection() { + let mut s = s(); + let id = s.execute("insert.shape", json!({"kind": "rectangle", "at": "A1"})).unwrap()["shape"].clone(); + let id_num = id.as_u64().unwrap() as u32; + let shape_state = |session: &Session| { + let doc = session.doc().unwrap(); + let shape = doc.wb.active().unwrap().shapes.iter().find(|shape| shape.id == id_num).unwrap(); + (shape.anchor, shape.rotation) + }; + + // Rotation remains available on an unprotected sheet. + s.execute("object.move", json!({"kind": "shape", "id": id_num, "at": "B2", "rotation": 45})).unwrap(); + let (anchor, rotation) = shape_state(&s); + assert_eq!(rotation, 45.0); + assert_eq!(anchor.cell, CellRef::parse("B2").unwrap()); + s.execute("edit.undo", json!({})).unwrap(); + + s.execute("review.protectSheet", json!({})).unwrap(); + let before = shape_state(&s); + let undo_len = s.doc().unwrap().undo.len(); + + let result = s.execute("object.move", json!({"kind": "shape", "id": id_num, "at": "C3", "rotation": 90})); + assert!(result.is_err(), "rotation should be rejected on a protected sheet"); + assert_eq!(shape_state(&s), before, "a rejected rotation leaves the shape unchanged"); + assert_eq!(s.doc().unwrap().undo.len(), undo_len); +} + #[test] fn editing_quote_prefixed_text_keeps_it_text() { let mut s = s(); @@ -6712,6 +6762,7 @@ fn a_script_cannot_switch_windows() { assert_eq!(v(&s, "A1"), Value::number(2.0)); } +mod chart_data; mod controls; mod equation; mod json_golden; diff --git a/crates/engine/src/tests/chart_data.rs b/crates/engine/src/tests/chart_data.rs new file mode 100644 index 0000000000..f8b03124b2 --- /dev/null +++ b/crates/engine/src/tests/chart_data.rs @@ -0,0 +1,177 @@ +//! A chart's data as blocks on the sheet, and `chart.setValuesRange`, which dragging a corner of a +//! selected chart's values outline runs (#4389, #4390). + +use gridcraft_core::RangeRef; +use gridcraft_model::{Chart, Color}; +use serde_json::json; + +use super::s; +use crate::Session; +use crate::chart_data::{ChartData, chart_data}; + +fn r(a: &str) -> RangeRef { + RangeRef::parse(a).unwrap() +} + +fn chart(s: &Session) -> Chart { + s.doc().unwrap().wb.active().unwrap().charts[0].clone() +} + +fn data(s: &Session) -> Option { + chart_data(&s.doc().unwrap().wb, 0, &chart(s)) +} + +/// Points each plotted series has, as the chart resolves them. +fn points(s: &Session) -> Vec { + gridcraft_chart::resolve(&s.doc().unwrap().wb, 0, &chart(s)).series.iter().map(|se| se.values.len()).collect() +} + +/// 10..80 down A1:A8, charted from A1:A5 only. +fn single_column() -> Session { + let mut s = s(); + let values: Vec<_> = (1..=8).map(|i| json!([i * 10])).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + s.execute("selection.set", json!({"range": "A1:A5"})).unwrap(); + s.execute("insert.chart", json!({"type": "column"})).unwrap(); + s +} + +/// Region names across row 1, quarters down column A, charted from A1:C4. +fn table() -> Session { + let mut s = s(); + s.execute( + "range.setValues", + json!({"range": "A1", "values": [ + ["", "North", "South", "East"], + ["Q1", 10, 15, 12], + ["Q2", 20, 25, 22], + ["Q3", 30, 35, 32], + ["Q4", 40, 45, 42], + ["Q5", 50, 55, 52], + ]}), + ) + .unwrap(); + s.execute("selection.set", json!({"range": "A1:C4"})).unwrap(); + s.execute("insert.chart", json!({"type": "column"})).unwrap(); + s +} + +#[test] +fn a_plain_column_chart_is_one_values_block() { + let s = single_column(); + assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("A1:A5"), by_rows: false, categories: None, names: None })); +} + +#[test] +fn a_table_chart_has_names_categories_and_values_blocks() { + let s = table(); + assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:C4"), by_rows: false, categories: Some(r("A2:A4")), names: Some(r("B1:C1")) })); +} + +#[test] +fn dragging_the_values_down_plots_the_new_rows_and_undo_puts_them_back() { + let mut s = single_column(); + assert_eq!(points(&s), [5]); + let out = s.execute("chart.setValuesRange", json!({"range": "A1:A8"})).unwrap(); + assert_eq!(out["values"], "Sheet1!A1:A8"); + assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$8"); + assert_eq!(points(&s), [8]); + assert_eq!(data(&s).unwrap().values, r("A1:A8")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(points(&s), [5]); + assert_eq!(chart(&s).series[0].values, "Sheet1!$A$1:$A$5"); +} + +#[test] +fn a_wider_block_adds_series_and_existing_series_keep_their_formatting() { + let mut s = table(); + s.execute("chart.formatSelection", json!({"series": 1, "color": "#C00000"})).unwrap(); + let south = chart(&s).series[1].color; + assert!(south.is_some()); + s.execute("chart.setValuesRange", json!({"range": "B2:D6"})).unwrap(); + let c = chart(&s); + assert_eq!(c.series.len(), 3); + assert_eq!(c.series[1].color, south, "South keeps its colour"); + assert_eq!(c.series[2].color, None::, "the new series takes the automatic colour"); + let names: Vec<_> = c.series.iter().map(|se| se.name.clone().unwrap()).collect(); + assert_eq!(names, ["Sheet1!$B$1", "Sheet1!$C$1", "Sheet1!$D$1"], "names follow along the header row"); + assert!(c.series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "labels span the new points"); + assert_eq!(c.series[2].values, "Sheet1!$D$2:$D$6"); + assert_eq!(c.source.as_deref(), Some("Sheet1!A1:D6"), "Switch Row/Column sees the moved blocks"); + assert_eq!(points(&s), [5, 5, 5]); + assert_eq!(data(&s), Some(ChartData { sheet: 0, values: r("B2:D6"), by_rows: false, categories: Some(r("A2:A6")), names: Some(r("B1:D1")) })); + // A narrower block drops the last series. + s.execute("chart.setValuesRange", json!({"range": "B2:B3"})).unwrap(); + let c = chart(&s); + assert_eq!(c.series.len(), 1); + assert_eq!(c.series[0].categories.as_deref(), Some("Sheet1!$A$2:$A$3")); + s.execute("chart.switchRowColumn", json!({})).unwrap(); +} + +#[test] +fn series_in_rows_grow_across_the_columns() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:E2"})).unwrap(); + s.execute("insert.chart", json!({"type": "line"})).unwrap(); + assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:E2"), true))); + s.execute("chart.setValuesRange", json!({"range": "A1:G2"})).unwrap(); + assert_eq!(points(&s), [7, 7]); + assert_eq!(chart(&s).series[1].values, "Sheet1!$A$2:$G$2"); +} + +/// Changes the first chart on the first sheet in place, as a file can leave it. +fn edit_chart(s: &mut Session, f: impl FnOnce(&mut Chart)) { + let wb = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().wb); + f(&mut wb.sheet_mut(0).unwrap().charts[0]); +} + +#[test] +fn category_labels_written_with_and_without_equals_are_one_block() { + let mut s = table(); + edit_chart(&mut s, |c| c.series[1].categories = Some("=Sheet1!$A$2:$A$4".into())); + assert_eq!(data(&s).unwrap().categories, Some(r("A2:A4"))); + s.execute("chart.setValuesRange", json!({"range": "B2:C6"})).unwrap(); + assert!(chart(&s).series.iter().all(|se| se.categories.as_deref() == Some("Sheet1!$A$2:$A$6")), "both series' labels follow"); +} + +#[test] +fn series_read_in_rows_stay_resizable_after_shrinking_to_one_cell_each() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]})).unwrap(); + s.execute("selection.set", json!({"range": "A1:E2"})).unwrap(); + s.execute("insert.chart", json!({"type": "line"})).unwrap(); + // A file can carry series in rows without saying so; the layout is read from the series. + edit_chart(&mut s, |c| c.by_rows = false); + assert_eq!(data(&s).map(|d| d.by_rows), Some(true)); + s.execute("chart.setValuesRange", json!({"range": "A1:A2"})).unwrap(); + assert!(chart(&s).by_rows); + assert_eq!(data(&s).map(|d| (d.values, d.by_rows)), Some((r("A1:A2"), true)), "still one block, still in rows"); + s.execute("chart.setValuesRange", json!({"range": "A1:C2"})).unwrap(); + assert_eq!(points(&s), [3, 3]); +} + +#[test] +fn set_values_range_refuses_what_it_cannot_do() { + let mut s = table(); + let before = chart(&s); + for (params, why) in [ + (json!({}), "missing `range`"), + (json!({"range": "not a range"}), "not a range"), + (json!({"range": "A1:Z100000"}), "too large"), + (json!({"range": "A1:JA2"}), "too large"), + (json!({"range": "Sheet2!B2:C4"}), ""), + (json!({"chart": 999, "range": "B2:C4"}), "chart"), + ] { + let err = s.execute("chart.setValuesRange", params.clone()).unwrap_err(); + assert!(err.to_string().contains(why), "{params}: {err}"); + assert_eq!(chart(&s), before, "{params} left the chart as it was"); + } + // Series with a gap between them are not one block. + s.execute("selection.set", json!({"range": "A1:D4"})).unwrap(); + s.execute("chart.selectData", json!({"range": "A1:D4"})).unwrap(); + s.execute("chart.selectData", json!({"removeSeries": [1]})).unwrap(); + assert_eq!(data(&s), None); + let err = s.execute("chart.setValuesRange", json!({"range": "B2:C4"})).unwrap_err(); + assert!(err.to_string().contains("not one block"), "{err}"); +} diff --git a/crates/functions/src/financial/tests.rs b/crates/functions/src/financial/tests.rs index a12e31022e..011d8f3da0 100644 --- a/crates/functions/src/financial/tests.rs +++ b/crates/functions/src/financial/tests.rs @@ -33,6 +33,82 @@ fn tvm() { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } +/// RATE with the given arguments, as a number or an error. +fn rate_of(args: &[f64]) -> Value { + ev("RATE", args.iter().map(|x| n(*x)).collect()) +} + +#[track_caller] +fn rate_is(args: &[f64], expected: f64) { + close_tol(rate_of(args), expected, 1e-15); +} + +/// Expected values observed in Excel 365 with these synthetic inputs. +#[test] +fn rate_follows_excel_iteration() { + // No payments and a zero future value: the answer is -100%, which the iteration + // approaches without reaching. Excel returns the last iterate, bit for bit. + rate_is(&[5.0, 0.0, -100.0, 0.0], -0.999_999_409_145_182_5); + rate_is(&[3.0, 0.0, -50.0, 0.0], -0.999_999_744_782_979_9); + rate_is(&[10.0, 0.0, -1.0, 0.0], -0.999_998_741_101_371_3); + rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, 0.5], -0.999_999_408_783_809_4); + rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, -0.99], -0.999_999_411_730_630_3); + // Second starting point goes the other way when the equation is positive at the guess. + rate_is(&[5.0, 0.0, 100.0, 0.0], -0.999_999_409_810_240_3); + rate_is(&[5.0, 0.0, -100.0, 1e-29], -0.999_999_260_333_075_4); + rate_is(&[5.0, 0.0, -100.0, 1e4], 1.511_886_431_510_563_3); + rate_is(&[4.0, 0.0, -1.0, 100.0], 2.162_277_660_168_009); + // Within 1e-7 by step but not by value: Excel keeps going. + rate_is(&[5.0, 0.0, -1e25, 0.0], -0.999_999_628_525_605_1); + // 200 steps without converging: the last iterate when it is within 1e-4, else #NUM!. + rate_is(&[20.0, 0.0, -1.0, 0.0], -0.999_112_071_912_539_3); + rate_is(&[36.0, 0.0, -1.0, 0.0, 0.0, -0.994], -0.999_875_315_309_626_9); + is_err(rate_of(&[12.0, 0.0, -1.0, 0.0]), CellError::Num); + is_err(rate_of(&[25.0, 0.0, -1.0, 0.0]), CellError::Num); + is_err(rate_of(&[20.0, 0.0, -1e60, 0.0]), CellError::Num); + // Large rates the iteration can't reach are #NUM! in Excel. + is_err(rate_of(&[4.0, 0.0, -0.0001, 100.0]), CellError::Num); + is_err(rate_of(&[5.0, 0.0, -100.0, 1e5]), CellError::Num); + is_err(rate_of(&[10.0, -300.0, 1000.0]), CellError::Num); + // ...but are found from a closer guess. + rate_is(&[4.0, 0.0, -0.1, 100.0, 0.0, 4.0], 4.623_413_251_903_489); + close_tol(rate_of(&[10.0, -300.0, 1000.0, 0.0, 0.0, 0.3]), 0.273_198_424_105_560_4, 1e-12); + // Converging on a rate at or below -100% (or within 1e-7 of it) is #NUM!. + is_err(rate_of(&[1.0, 0.0, -1.0, 0.0]), CellError::Num); + is_err(rate_of(&[10.0, -1000.0, 1000.0]), CellError::Num); + is_err(rate_of(&[1.0, 0.0, -100.0, 1e-5]), CellError::Num); + rate_is(&[1.0, 0.0, -100.0, 2e-5], -0.999_999_8); + is_err(rate_of(&[5.0, 0.0, -1e30, 0.0]), CellError::Num); + is_err(rate_of(&[0.5, 0.0, -1.0, 0.0]), CellError::Num); + // A value that never gets near zero is #NUM!, however small the step. + is_err(rate_of(&[4.0, 0.0, 100.0, 100.0]), CellError::Num); + is_err(rate_of(&[4.0, 0.0, -1e-12, 1e-6]), CellError::Num); + rate_is(&[4.0, 0.0, -1e-14, 1e-8], 0.099_000_000_283_235_72); + // Subnormal steps are flushed to zero. + rate_is(&[3.0, 0.0, -1e-305, 0.0], 0.101); + is_err(rate_of(&[4.0, 0.0, 0.0, 100.0]), CellError::Num); + // Guess at or below -1 is #VALUE!; type is 0 or anything else (1). + is_err(rate_of(&[10.0, -100.0, 1000.0, 0.0, 0.0, -1.0]), CellError::Value); + is_err(rate_of(&[0.0, -100.0, 1000.0]), CellError::Num); + // Excel does not step the second point back to -1: a fractional nper with a guess near -1 is #NUM! + // even though a root exists at -0.99, and the same case from a guess of -0.99 finds it. + is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.9995]), CellError::Num); + is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.5]), CellError::Num); + close_tol(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.99]), -0.99, 1e-7); + assert_eq!(rate_of(&[10.0, -100.0, 1000.0, 0.0, 2.0]), rate_of(&[10.0, -100.0, 1000.0, 0.0, 1.0])); + // Ordinary loans, and large amounts that can't get within 1e-7 of zero. + close_tol(rate_of(&[360.0, -1000.0, 150000.0]), 0.005_850_253_376_759_637, 1e-11); + close_tol(rate_of(&[360.0, -1000.0, 150000.0, 0.0, 1.0]), 0.005_898_953_457_098_463, 1e-11); + close_tol(rate_of(&[1000.0, -1e6, 1e8]), 0.009_999_522_655_994_865, 1e-12); + close_tol(rate_of(&[360.0, -1e9, 1.5e11]), 0.005_850_253_376_759_668, 1e-12); + close_tol(rate_of(&[10.0, -50.0, 1000.0]), -0.109_560_293_684_682_5, 1e-14); + // Roots at 0% come out as rounding noise in both, so only the absolute size matters. + match rate_of(&[10.0, -100.0, 1000.0]) { + Value::Number(x) => assert!(x.abs() < 1e-8, "{x}"), + other => panic!("{other:?}"), + } +} + /// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across /// platforms). The old `(1 + rate)^nper` form was 25 to 91 ULPs off on these, enough to flip a loan schedule's final `IF(p - SUM(r) > 0, ...)`. #[test] diff --git a/crates/functions/src/financial/tvm.rs b/crates/functions/src/financial/tvm.rs index 872e7cbeb1..d8aa2f9977 100644 --- a/crates/functions/src/financial/tvm.rs +++ b/crates/functions/src/financial/tvm.rs @@ -218,21 +218,85 @@ fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R { Err(CellError::Num) } +/// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus +/// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to +/// judge how close to zero the first can get in floating point. +fn rate_equation(r: f64, np: f64, pmt: f64, pv: f64, fv: f64, typ: f64) -> (f64, f64) { + if r == 0.0 { + return (pv + pmt * np + fv, pv.abs() + (pmt * np).abs() + fv.abs()); + } + let p = (1.0 + r).powf(np); + let (a, b) = (pv * p, pmt * (1.0 / r + typ) * (p - 1.0)); + (a + b + fv, a.abs() + b.abs() + fv.abs()) +} + +/// Excel works with subnormal numbers flushed to zero: a secant step that underflows doesn't +/// move. Observed with RATE(3,0,-1E-305,0), which is 0.101 (the second starting point). +fn flush_subnormal(x: f64) -> f64 { + if x.abs() < f64::MIN_POSITIVE { 0.0 } else { x } +} + +/// Excel's RATE solver, reconstructed by observing Excel with synthetic inputs (not from its +/// code; its documentation says only "iteration", 20 steps and 0.0000001): +/// +/// - A secant iteration starting at the guess and at the guess moved 0.001 toward a larger +/// value of the equation, for at most 200 steps. +/// - It stops at the first iterate that moved less than 1e-7 and where the equation is within +/// 1e-7 of zero (or as close as its terms allow, for very large amounts). Excel returns that +/// iterate, not the exact root, so a slowly converging case such as no payments and a zero +/// future value (exact answer -100%) gives a rate just above -1. +/// - The result must be above -1 by more than the tolerance; otherwise it is #NUM!. +/// - After 200 steps without that, Excel still returns the last iterate if it is within a +/// looser 1e-4 (step, equation value and distance above -1); otherwise #NUM!. So a root the +/// iteration can't reach (a very large rate) is #NUM! even though it exists. +fn rate_solve(f: impl Fn(f64) -> (f64, f64), guess: f64) -> R { + const STEPS: usize = 200; + const TOL: f64 = 1e-7; + const LOOSE: f64 = 1e-4; + let eval = |x: f64| { + let (y, size) = f(x); + if y.is_finite() { Ok((y, size)) } else { Err(CellError::Num) } + }; + let near_zero = |y: f64, size: f64| y.abs() < TOL || y.abs() <= 1e-12 * size; + let (mut x0, (mut f0, _)) = (guess, eval(guess)?); + let mut x1 = if f0 < 0.0 { guess + 0.001 } else { guess - 0.001 }; + let (mut f1, mut size1) = eval(x1)?; + for _ in 0..STEPS { + let den = flush_subnormal(f1 - f0); + if den == 0.0 { + // The secant is flat: done if the iteration had already settled. + if (x1 - x0).abs() < TOL && near_zero(f1, size1) && x1 - TOL > -1.0 { + return Ok(x1); + } + return Err(CellError::Num); + } + let x2 = x1 - flush_subnormal(f1 * (x1 - x0)) / den; + if !x2.is_finite() { + return Err(CellError::Num); + } + let (f2, size2) = eval(x2)?; + if (x2 - x1).abs() < TOL && near_zero(f2, size2) { + return if x2 - TOL > -1.0 { Ok(x2) } else { Err(CellError::Num) }; + } + (x0, f0, x1, f1, size1) = (x1, f1, x2, f2, size2); + } + if (x1 - x0).abs() < LOOSE && f1.abs() < LOOSE && x1 - LOOSE > -1.0 { + return Ok(x1); + } + Err(CellError::Num) +} + pub(super) fn rate(a: &[Arg], _c: &mut dyn Ctx) -> R { let (np, pmt, pv) = (num(a, 0)?, num(a, 1)?, num(a, 2)?); let (fv, typ, guess) = (opt_num(a, 3, 0.0)?, type_arg(a, 4)?, opt_num(a, 5, 0.1)?); if np <= 0.0 { return Err(CellError::Num); } - let f = |r: f64| { - if r.abs() < 1e-12 { - pv + pmt * np + fv - } else { - let p = (1.0 + r).powf(np); - pv * p + pmt * (1.0 + r * typ) * (p - 1.0) / r + fv - } - }; - num_val(solve_rate(f, guess)?) + // Excel: a guess at or below -100% is #VALUE!, not #NUM!. + if guess <= -1.0 { + return Err(CellError::Value); + } + num_val(rate_solve(|r| rate_equation(r, np, pmt, pv, fv, typ), guess)?) } pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { diff --git a/crates/model/src/features.rs b/crates/model/src/features.rs index 099bd440aa..d8bad07bc5 100644 --- a/crates/model/src/features.rs +++ b/crates/model/src/features.rs @@ -690,6 +690,9 @@ pub struct Shape { /// Outline visibility and text formatting (DrawingML `a:ln`, `a:bodyPr`, `a:pPr`, `a:rPr`). #[serde(default)] pub format: ShapeFormat, + /// Degrees clockwise about the anchor rect's centre, in `[0, 360)`. + #[serde(default)] + pub rotation: f32, /// An equation's layout, rebuilt from `text` and never saved. #[serde(skip)] pub math: EquationCache, diff --git a/crates/model/src/sheet.rs b/crates/model/src/sheet.rs index 409e93023c..b28d0c2ffa 100644 --- a/crates/model/src/sheet.rs +++ b/crates/model/src/sheet.rs @@ -946,6 +946,7 @@ mod tests { fill: Color::default(), line: Color::default(), text: String::new(), + rotation: 0.0, format: ShapeFormat::default(), math: EquationCache::default(), }), diff --git a/crates/ui-egui/src/chartview.rs b/crates/ui-egui/src/chartview.rs index 48f0846ae5..7d91d718d6 100644 --- a/crates/ui-egui/src/chartview.rs +++ b/crates/ui-egui/src/chartview.rs @@ -298,9 +298,12 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc None } -fn selection_frame(p: &Painter, r: Rect) { - let t = Tokens::get(p.ctx()); - p.rect_stroke(r, 0.0, Stroke::new(1.0, t.sheet_control_border), StrokeKind::Outside); - for h in crate::objects::Handle::ALL { - let c = h.pos(r); - p.circle_filled(c, 4.0, t.sheet_control_bg); - p.circle_stroke(c, 4.0, Stroke::new(1.0, t.sheet_control_border)); +/// The selected object's turn in degrees, and whether its frame shows a rotation handle and +/// resize handles (an ink stroke shows neither). +pub fn frame_of(sh: &Sheet, o: ObjRef) -> (f32, bool, bool) { + match sh.shapes.iter().find(|s| o.kind == ObjKind::Shape && s.id == o.id) { + Some(s) => (s.rotation, s.kind != ShapeKind::Ink, s.kind != ShapeKind::Ink), + None => (0.0, false, true), } } +/// How far from a corner of a selected chart's values outline a press still grabs it. +const DATA_HANDLE_REACH: f32 = 6.0; +/// The corners of a values outline, which drag it (#4389). +const DATA_HANDLES: [crate::objects::Handle; 4] = + [crate::objects::Handle::TopLeft, crate::objects::Handle::TopRight, crate::objects::Handle::BottomLeft, crate::objects::Handle::BottomRight]; + +/// The selected chart and its data as blocks on sheet `si` (`sh`), while the chart lies on screen +/// within `clip`: the blocks a drag of its values outline previews, else where they are. `None` +/// when no chart is selected, its data is on another sheet or its series are not one block. +pub(crate) fn selected_chart_data( + app: &SheetApp, + geo: &Geo, + wb: &Workbook, + si: usize, + sh: &Sheet, + clip: Rect, +) -> Option<(u32, gridcraft_engine::chart_data::ChartData)> { + if objects_hidden(wb) { + return None; + } + let id = app.selected_chart()?; + let ch = sh.charts.iter().find(|ch| ch.id == id)?; + let dragged = match app.grid.drag { + crate::grid::Drag::ChartData { chart, to, .. } if chart == id => Some(to), + _ => None, + }; + // A drag that scrolls the chart away keeps its preview: the block is still being dragged. + if dragged.is_none() && !anchor_rect(geo, sh, &ch.anchor).intersects(clip) { + return None; + } + let data = gridcraft_engine::chart_data::chart_data(wb, si, ch).filter(|d| d.sheet == si)?; + Some((id, dragged.flatten().map_or(data, |to| data.moved(to)))) +} + +/// Where the handle on corner `h` of the values outline `rr` is painted. +fn data_handle_rect(h: crate::objects::Handle, rr: Rect) -> Rect { + Rect::from_center_size(h.pos(rr), vec2(7.0, 7.0)) +} + +/// Outlines a chart's data as Excel does: series names in red, category labels in purple and +/// values in blue (#4390), with a handle on each corner of the values (#4389). Each pane clips +/// its own part, so frozen panes show the block once. +fn paint_chart_data(p: &Painter, geo: &Geo, sh: &Sheet, data: &gridcraft_engine::chart_data::ChartData) { + let t = Tokens::get(p.ctx()); + let blocks = [(data.names, 1, false), (data.categories, 2, false), (Some(data.values), 0, true)]; + for (range, color, handles) in blocks.into_iter().filter_map(|(r, c, h)| r.map(|r| (r, t.ref_color(c, true), h))) { + let rr = geo.range_rect(sh, range); + for pane in geo.range_panes(range) { + let pp = p.with_clip_rect(pane.intersect(p.clip_rect())); + pp.rect_stroke(rr, 0.0, Stroke::new(1.5, color), StrokeKind::Inside); + if handles { + for h in DATA_HANDLES { + pp.rect_filled(data_handle_rect(h, rr), 0.0, Color32::WHITE); + pp.rect_filled(data_handle_rect(h, rr).shrink(1.0), 0.0, color); + } + } + } + } +} + +/// The corner of the selected chart's values outline under `p`, with the chart and its values +/// block. Like [`hit`], only over the cell area and while objects show; the caller asks +/// [`hit`] first, since objects paint over the outline. +pub fn chart_data_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(u32, gridcraft_engine::core::RangeRef, crate::objects::Handle)> { + if !geo.cells.contains(p) { + return None; + } + let wb = &app.session.active()?.wb; + let (id, data) = selected_chart_data(app, geo, wb, wb.active_sheet(), sh, geo.cells)?; + let rr = geo.range_rect(sh, data.values); + // Only a corner some pane paints: with frozen panes, a corner scrolled under the frozen band + // is hidden, and the frozen cells it lies under keep the press. + let panes = geo.range_panes(data.values); + DATA_HANDLES + .into_iter() + .filter(|h| panes.iter().any(|pane| pane.intersects(data_handle_rect(*h, rr)))) + .map(|h| (h, h.pos(rr).distance(p))) + .filter(|(_, d)| *d <= DATA_HANDLE_REACH) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(h, _)| (id, data.values, h)) +} + /// Where object `o` sits on the sheet (logical coordinates), when it exists on `sh`. pub fn object_rect(geo: &Geo, sh: &Sheet, o: ObjRef) -> Option { sh.object_anchor(o).map(|a| anchor_rect(geo, sh, &a)) @@ -565,7 +654,22 @@ pub fn selected_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option } let o = app.selected_object?; let r = object_rect(geo, sh, o)?; - crate::objects::handle_at(r, p).map(|h| (o, r, h)) + let (deg, _, resizes) = frame_of(sh, o); + if !resizes { + return None; + } + crate::objects::handle_at(r, crate::frame::turn(p, r.center(), -deg)).map(|h| (o, r, h)) +} + +/// The selected object and its rect when `p` is on its rotation handle. +pub fn selected_rotate(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Rect)> { + if !geo.cells.contains(p) || app.session.active().is_some_and(|d| objects_hidden(&d.wb)) { + return None; + } + let o = app.selected_object?; + let r = object_rect(geo, sh, o)?; + let (deg, rotates, _) = frame_of(sh, o); + (rotates && matches!(crate::frame::grab_at(r, deg, true, p), Some(crate::frame::Grab::Rotate))).then_some((o, r)) } /// The topmost object under `p` and its rect: form controls paint on top, so they are hit first, @@ -601,7 +705,7 @@ pub fn hit(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Re } for s in sh.shapes.iter().rev() { let r = anchor_rect(geo, sh, &s.anchor); - if r.expand(3.0).contains(p) { + if r.expand(3.0).contains(crate::frame::turn(p, r.center(), -s.rotation)) { let kind = if s.kind == ShapeKind::Equation { ObjKind::Equation } else { ObjKind::Shape }; return Some((ObjRef::new(kind, s.id), r)); } @@ -615,6 +719,72 @@ pub(crate) fn ink_color(line: Color32, width_pt: f32) -> Color32 { if width_pt > 8.0 { line.gamma_multiply(0.45) } else { line } } +/// Turn everything painted on `p`'s layer since `start` by `deg` clockwise about `c`. +fn turn_painted(p: &Painter, start: egui::layers::ShapeIdx, c: Pos2, deg: f32) { + let end = p.add(egui::Shape::Noop).0; + let clip = p.clip_rect(); + p.ctx().graphics_mut(|g| { + let list = g.entry(p.layer_id()); + for i in start.0..end { + list.mutate_shape(egui::layers::ShapeIdx(i), |cs| { + // A turned shape reaches past its own box: clip it to the sheet only. + cs.clip_rect = clip; + turn_shape(&mut cs.shape, c, deg); + }); + } + }); +} + +fn turn_shape(shape: &mut egui::Shape, c: Pos2, deg: f32) { + use egui::Shape; + let t = |q: &mut Pos2| *q = crate::frame::turn(*q, c, deg); + match shape { + Shape::Noop | Shape::Callback(_) | Shape::Band(_) => {} + Shape::Vec(v) => v.iter_mut().for_each(|s| turn_shape(s, c, deg)), + Shape::Circle(k) => t(&mut k.center), + Shape::Ellipse(e) => { + let pts = (0..64) + .map(|i| { + let a = i as f32 / 64.0 * std::f32::consts::TAU; + crate::frame::turn(e.center + vec2(e.radius.x * a.cos(), e.radius.y * a.sin()), c, deg) + }) + .collect(); + *shape = Shape::Path(PathShape::convex_polygon(pts, e.fill, e.stroke)); + } + Shape::LineSegment { points, .. } => points.iter_mut().for_each(t), + Shape::Path(path) => path.points.iter_mut().for_each(t), + Shape::Rect(r) => { + let pts = rounded_rect_points(r.rect, f32::from(r.corner_radius.nw)).into_iter().map(|q| crate::frame::turn(q, c, deg)).collect(); + *shape = Shape::Path(PathShape::convex_polygon(pts, r.fill, r.stroke)); + } + Shape::Text(text) => { + t(&mut text.pos); + text.angle += deg.to_radians(); + } + Shape::Mesh(m) => std::sync::Arc::make_mut(m).vertices.iter_mut().for_each(|v| t(&mut v.pos)), + Shape::QuadraticBezier(b) => b.points.iter_mut().for_each(t), + Shape::CubicBezier(b) => b.points.iter_mut().for_each(t), + } +} + +/// The outline of `r` with corners rounded by `radius`, clockwise from the top left. +fn rounded_rect_points(r: Rect, radius: f32) -> Vec { + let rad = radius.min(r.width() / 2.0).min(r.height() / 2.0).max(0.0); + if rad < 0.5 { + return vec![r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()]; + } + let corners = [ + (pos2(r.left() + rad, r.top() + rad), 180.0_f32), + (pos2(r.right() - rad, r.top() + rad), 270.0), + (pos2(r.right() - rad, r.bottom() - rad), 0.0), + (pos2(r.left() + rad, r.bottom() - rad), 90.0), + ]; + corners + .into_iter() + .flat_map(|(o, from)| (0..=8).map(move |i| (from + i as f32 * 90.0 / 8.0).to_radians()).map(move |a| o + vec2(a.cos(), a.sin()) * rad)) + .collect() +} + #[cfg(test)] pub(crate) mod tests { use std::cell::Cell; diff --git a/crates/ui-egui/src/dialogs/find.rs b/crates/ui-egui/src/dialogs/find.rs index 394cf52119..9d67aeaa86 100644 --- a/crates/ui-egui/src/dialogs/find.rs +++ b/crates/ui-egui/src/dialogs/find.rs @@ -1,8 +1,23 @@ +use egui::Modifiers; + use super::show::ok_cancel; use super::{Dialog, Json, Key, SheetApp, json}; /// Draws the Find/Replace form with case, whole-cell and workbook options, requests field focus once, and runs find/replace with the current parameters. pub(super) fn find(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog) { + // The dialog stays open over the sheet, so Undo and Redo reach the workbook (a Replace All + // is undone without closing it first); inside a text box they edit the typed text instead. + // A modal message blocks workbook shortcuts; otherwise use the grid's own shortcut table. + if app.message.is_none() && !ui.ctx().text_edit_focused() { + let pressed = ui.input_mut(|i| { + [(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z), (Modifiers::COMMAND, Key::Z), (Modifiers::COMMAND, Key::Y)] + .into_iter() + .find(|&(m, key)| i.consume_key(m, key)) + }); + if let Some((m, key)) = pressed { + crate::ribbon::shortcut(app, key, m); + } + } ui.horizontal(|ui| { for tab in ["Find", "Replace"] { if ui.selectable_label(d.tab == tab, tab).clicked() { diff --git a/crates/ui-egui/src/frame.rs b/crates/ui-egui/src/frame.rs new file mode 100644 index 0000000000..915376662b --- /dev/null +++ b/crates/ui-egui/src/frame.rs @@ -0,0 +1,262 @@ +//! The selection frame around a floating object (chart, picture, shape, slicer): its eight +//! handles, the rotation handle above a shape, which one a press grabs, and the rect a handle +//! drag gives. A turned frame is the rect turned about its centre, `deg` clockwise. + +use egui::{CursorIcon, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; + +/// Handle radius and the radius a press grabs a handle within (screen points). +pub const HANDLE_R: f32 = 4.0; +const GRAB_R: f32 = 10.0; +/// Frames smaller than this (screen points) show only corner handles on that axis. +const EDGE_HANDLES_FROM: f32 = 40.0; +/// How far the rotation handle sits above the frame's top edge (screen points), and the step +/// Shift snaps the angle to (degrees). +const ROTATE_GAP: f32 = 22.0; +pub const SNAP_DEG: f32 = 15.0; + +/// Screen point `p` turned `deg` degrees clockwise about `c`. +pub fn turn(p: Pos2, c: Pos2, deg: f32) -> Pos2 { + let (s, k) = deg.to_radians().sin_cos(); + let (u, v) = (p.x - c.x, p.y - c.y); + pos2(c.x + u * k - v * s, c.y + u * s + v * k) +} + +/// One of the eight handles: `x` / `y` are -1 (left/top), 0 (middle) or 1 (right/bottom). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Handle { + pub x: i8, + pub y: i8, +} + +impl Handle { + pub const ALL: [Handle; 8] = [ + Handle { x: -1, y: -1 }, + Handle { x: 0, y: -1 }, + Handle { x: 1, y: -1 }, + Handle { x: 1, y: 0 }, + Handle { x: 1, y: 1 }, + Handle { x: 0, y: 1 }, + Handle { x: -1, y: 1 }, + Handle { x: -1, y: 0 }, + ]; + pub fn is_corner(self) -> bool { + self.x != 0 && self.y != 0 + } + /// The resize cursor, picked for the handle's direction on a frame turned `deg`. + pub fn cursor(self, deg: f32) -> CursorIcon { + let a = f32::from(self.y).atan2(f32::from(self.x)).to_degrees() + deg; + // Eight compass sectors of 45°; opposite sectors share a cursor. + match ((a / 45.0).round() as i32).rem_euclid(4) { + 0 => CursorIcon::ResizeHorizontal, + 1 => CursorIcon::ResizeNwSe, + 2 => CursorIcon::ResizeVertical, + _ => CursorIcon::ResizeNeSw, + } + } + pub fn at(self, f: Rect) -> Pos2 { + let k = |v: i8| (f32::from(v) + 1.0) / 2.0; + pos2(f.min.x + f.width() * k(self.x), f.min.y + f.height() * k(self.y)) + } + pub fn at_turned(self, f: Rect, deg: f32) -> Pos2 { + turn(self.at(f), f.center(), deg) + } +} + +/// What a press on a selected object grabbed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Grab { + Move, + Resize(Handle), + Rotate, +} + +impl Grab { + pub fn cursor(self, deg: f32) -> CursorIcon { + match self { + Grab::Move => CursorIcon::Move, + Grab::Resize(h) => h.cursor(deg), + Grab::Rotate => CursorIcon::Crosshair, + } + } +} + +/// The handles a frame shows: corners always, edge middles when there's room. +pub fn handles(f: Rect) -> impl Iterator { + let (wide, tall) = (f.width() >= EDGE_HANDLES_FROM, f.height() >= EDGE_HANDLES_FROM); + Handle::ALL.into_iter().filter(move |h| (h.x != 0 || wide) && (h.y != 0 || tall)) +} + +/// Where the rotation handle of frame `f` turned `deg` is: above the middle of its top edge. +pub fn rotate_handle(f: Rect, deg: f32) -> Pos2 { + turn(pos2(f.center().x, f.min.y - ROTATE_GAP), f.center(), deg) +} + +/// The handle of frame `f` turned `deg` under screen point `p`; `rotate` offers the rotation +/// handle too. +pub fn grab_at(f: Rect, deg: f32, rotate: bool, p: Pos2) -> Option { + if rotate && rotate_handle(f, deg).distance(p) <= GRAB_R { + return Some(Grab::Rotate); + } + let d = |h: &Handle| h.at_turned(f, deg).distance(p); + handles(f).filter(|h| d(h) <= GRAB_R).min_by(|a, b| d(a).total_cmp(&d(b))).map(Grab::Resize) +} + +/// The angle (degrees clockwise, `[0, 360)`) that points frame `f`'s rotation handle at `p`, +/// by whole degrees or, with `snap`, by [`SNAP_DEG`]. +pub fn angle_to(f: Rect, p: Pos2, snap: bool) -> f32 { + let d = p - f.center(); + // The handle is straight up (-90°) when unturned. + let deg = d.y.atan2(d.x).to_degrees() + 90.0; + let step = if snap { SNAP_DEG } else { 1.0 }; + ((deg / step).round() * step).rem_euclid(360.0) +} + +/// Draw frame `f` turned `deg`: outline, handles and, with `rotate`, the rotation handle. +pub fn paint(p: &Painter, f: Rect, deg: f32, rotate: bool, resize: bool) { + let line = Stroke::new(1.0, egui::Color32::from_gray(120)); + if deg == 0.0 { + p.rect_stroke(f, 0.0, line, StrokeKind::Outside); + } else { + let c = f.center(); + let pts = [f.left_top(), f.right_top(), f.right_bottom(), f.left_bottom(), f.left_top()].map(|q| turn(q, c, deg)); + p.add(egui::Shape::line(pts.to_vec(), line)); + } + let knob = |c: Pos2| { + p.circle_filled(c, HANDLE_R, egui::Color32::WHITE); + p.circle_stroke(c, HANDLE_R, Stroke::new(1.0, egui::Color32::from_gray(100))); + }; + if rotate { + let r = rotate_handle(f, deg); + p.line_segment([turn(f.center_top(), f.center(), deg), r], line); + knob(r); + // A circling arrow: three quarters of a ring. + let ring: Vec = (0..=12).map(|i| r + vec2((i as f32 * 0.4).cos(), (i as f32 * 0.4).sin()) * (HANDLE_R * 0.55)).collect(); + p.add(egui::Shape::line(ring, Stroke::new(1.0, egui::Color32::from_gray(80)))); + } + if resize { + for h in handles(f) { + knob(h.at_turned(f, deg)); + } + } +} + +/// [`resized`] for a frame turned `deg`: the drag is taken along the frame's own axes, and the +/// handle opposite the grabbed one stays where it is. +pub fn resized_turned(r: Rect, deg: f32, h: Handle, d: egui::Vec2, min: f32, keep_aspect: bool) -> Rect { + resized_turned_by_min(r, deg, h, d, egui::Vec2::splat(min), keep_aspect) +} + +/// Axis-aware version for objects with a zero-height or zero-width minimum. +pub(crate) fn resized_turned_by_min(r: Rect, deg: f32, h: Handle, d: egui::Vec2, min: egui::Vec2, keep_aspect: bool) -> Rect { + if deg == 0.0 { + return resized_by_min(r, h, d, min, keep_aspect); + } + let local = turn(pos2(d.x, d.y), Pos2::ZERO, -deg).to_vec2(); + let n = resized_by_min(r, h, local, min, keep_aspect); + let opp = Handle { x: -h.x, y: -h.y }; + n.translate(opp.at_turned(r, deg) - opp.at_turned(n, deg)) +} + +/// `r` with handle `h` dragged by `d`; the opposite edges stay put. Never smaller than `min`; +/// `keep_aspect` keeps the proportions when a corner is dragged. +pub fn resized(r: Rect, h: Handle, d: egui::Vec2, min: f32, keep_aspect: bool) -> Rect { + resized_by_min(r, h, d, egui::Vec2::splat(min), keep_aspect) +} + +fn resized_by_min(r: Rect, h: Handle, d: egui::Vec2, min: egui::Vec2, keep_aspect: bool) -> Rect { + let (mut x0, mut y0, mut x1, mut y1) = (r.min.x, r.min.y, r.max.x, r.max.y); + match h.x { + -1 => x0 = (x0 + d.x).min(x1 - min.x), + 1 => x1 = (x1 + d.x).max(x0 + min.x), + _ => {} + } + match h.y { + -1 => y0 = (y0 + d.y).min(y1 - min.y), + 1 => y1 = (y1 + d.y).max(y0 + min.y), + _ => {} + } + if keep_aspect && h.is_corner() && r.width() > 0.0 && r.height() > 0.0 { + // Follow whichever side changed more. + let (kx, ky) = ((x1 - x0) / r.width(), (y1 - y0) / r.height()); + let k = if (kx - 1.0).abs() >= (ky - 1.0).abs() { kx } else { ky }; + let k = k.max(min.x / r.width()).max(min.y / r.height()); + let (w, hh) = (r.width() * k, r.height() * k); + if h.x < 0 { + x0 = x1 - w; + } else { + x1 = x0 + w; + } + if h.y < 0 { + y0 = y1 - hh; + } else { + y1 = y0 + hh; + } + } + Rect::from_min_max(pos2(x0, y0), pos2(x1, y1)) +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::vec2; + + fn r() -> Rect { + Rect::from_min_size(pos2(100.0, 100.0), vec2(200.0, 100.0)) + } + + #[test] + fn the_left_handle_moves_only_the_left_edge() { + let n = resized(r(), Handle { x: -1, y: 0 }, vec2(-30.0, 50.0), 20.0, false); + assert_eq!(n, Rect::from_min_max(pos2(70.0, 100.0), pos2(300.0, 200.0))); + } + + #[test] + fn the_top_left_corner_never_crosses_the_opposite_edges() { + let n = resized(r(), Handle { x: -1, y: -1 }, vec2(500.0, 500.0), 20.0, false); + assert_eq!(n, Rect::from_min_max(pos2(280.0, 180.0), pos2(300.0, 200.0))); + } + + #[test] + fn shift_keeps_the_proportions() { + let n = resized(r(), Handle { x: 1, y: 1 }, vec2(200.0, 0.0), 20.0, true); + assert_eq!(n.size(), vec2(400.0, 200.0)); + assert_eq!(n.min, r().min); + } + + #[test] + fn small_frames_drop_the_edge_handles() { + let small = Rect::from_min_size(pos2(0.0, 0.0), vec2(30.0, 100.0)); + assert!(handles(small).all(|h| h.x != 0)); + assert_eq!(handles(r()).count(), 8); + } + + #[test] + fn cursors_follow_the_turned_handle() { + let right = Handle { x: 1, y: 0 }; + assert_eq!(right.cursor(0.0), CursorIcon::ResizeHorizontal); + assert_eq!(right.cursor(90.0), CursorIcon::ResizeVertical); + assert_eq!(right.cursor(45.0), CursorIcon::ResizeNwSe); + assert_eq!(Handle { x: 1, y: -1 }.cursor(0.0), CursorIcon::ResizeNeSw); + } + + #[test] + fn the_rotation_handle_points_at_the_pointer() { + let c = r().center(); + assert_eq!(angle_to(r(), c + vec2(0.0, -50.0), false), 0.0); + assert_eq!(angle_to(r(), c + vec2(50.0, 0.0), false), 90.0); + assert_eq!(angle_to(r(), c + vec2(-50.0, 0.0), false), 270.0); + assert_eq!(angle_to(r(), c + vec2(50.0, -40.0), true), 45.0); + assert_eq!(grab_at(r(), 0.0, true, rotate_handle(r(), 0.0)), Some(Grab::Rotate)); + assert_eq!(grab_at(r(), 0.0, false, rotate_handle(r(), 0.0)), None); + } + + #[test] + fn a_turned_resize_keeps_the_opposite_handle_in_place() { + let h = Handle { x: 1, y: 0 }; + let n = resized_turned(r(), 90.0, h, vec2(0.0, 40.0), 20.0, false); + // Turned 90°, the right handle points down: a downward drag widens the frame. + assert!((n.width() - 240.0).abs() < 0.01, "{n:?}"); + let opp = Handle { x: -1, y: 0 }; + assert!((opp.at_turned(n, 90.0) - opp.at_turned(r(), 90.0)).length() < 0.01); + } +} diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index 684b651fbc..477a4e26af 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -151,6 +151,20 @@ pub enum Drag { /// step of an earlier drag. stepped: bool, }, + /// Turning a shape about the centre of `rect` (its screen rect as the drag began). + Rotate { + obj: gridcraft_engine::model::ObjRef, + rect: Rect, + stepped: bool, + }, + /// Dragging a corner of the selected chart's values outline (#4389): `to` is the previewed + /// block, which the release gives the chart. + ChartData { + chart: u32, + orig: RangeRef, + corner: crate::objects::Handle, + to: Option, + }, } /// The fill a left-drag of the handle just made, which the Auto Fill Options button can redo diff --git a/crates/ui-egui/src/grid/cursor.rs b/crates/ui-egui/src/grid/cursor.rs index 38de611d8e..d6921599fa 100644 --- a/crates/ui-egui/src/grid/cursor.rs +++ b/crates/ui-egui/src/grid/cursor.rs @@ -57,7 +57,8 @@ fn drag_cursor(drag: &Drag, rtl: bool) -> Option { Drag::ResizeCol { .. } => Some(CursorIcon::ResizeColumn), Drag::ResizeRow { .. } => Some(CursorIcon::ResizeRow), Drag::Freeze { cols, .. } => Some(if *cols { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical }), - Drag::Object { handle: Some(h), .. } => Some(h.cursor(rtl)), + Drag::Rotate { .. } => Some(CursorIcon::Crosshair), + Drag::Object { handle: Some(h), .. } | Drag::ChartData { corner: h, .. } => Some(h.cursor(rtl)), } } @@ -81,13 +82,21 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin let on_cur_border = on_border(cur_rect, p) && border_panes.iter().any(|r| r.contains(p)); // The selected object's handles resize it; any object's body moves it. let idle = app.grid.drag == Drag::None && app.editor.is_none(); - let object_handle = if idle { crate::chartview::selected_handle(app, geo, sh, p).map(|(.., h)| h) } else { None }; + let object_handle = if idle { crate::chartview::selected_handle(app, geo, sh, p) } else { None }; let hit = if idle { crate::chartview::hit(app, geo, sh, p) } else { None }; // A form control works on click unless it is selected (or Ctrl or Cmd is held). let mods = ctx.input(|i| i.modifiers); let works = hit.is_some_and(|(o, _)| o.kind == ObjKind::Control && app.selected_object != Some(o) && !mods.command && !mods.ctrl); let on_object = hit.is_some(); - if let Some(h) = object_handle { + // A corner of the selected chart's values outline resizes the chart's data, where no object covers it. + let data_handle = if idle && !on_object { crate::chartview::chart_data_handle(app, geo, sh, p).map(|(.., h)| h) } else { None }; + let on_rotate = idle && crate::chartview::selected_rotate(app, geo, sh, p).is_some(); + if on_rotate { + ctx.set_cursor_icon(CursorIcon::Crosshair); + } else if let Some((o, _, h)) = object_handle { + let deg = crate::chartview::frame_of(sh, o).0; + ctx.set_cursor_icon(if deg == 0.0 { h.cursor(geo.rtl) } else { crate::frame::Handle { x: h.sides().0, y: h.sides().1 }.cursor(deg) }); + } else if let Some(h) = data_handle { ctx.set_cursor_icon(h.cursor(geo.rtl)); } else if works { ctx.set_cursor_icon(CursorIcon::PointingHand); diff --git a/crates/ui-egui/src/grid/interact.rs b/crates/ui-egui/src/grid/interact.rs index 9d61758d7a..f0ab7bc8ea 100644 --- a/crates/ui-egui/src/grid/interact.rs +++ b/crates/ui-egui/src/grid/interact.rs @@ -136,6 +136,13 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo if primary_drag || primary_clicked { // A drag is recognised only after the pointer has moved, so grab the object where the press began. let at = if primary_drag { pointer.press_origin().map(|p| geo.mirror_pos(p)).or(pos) } else { pos }; + if primary_drag + && let Some(p) = at + && let Some((obj, rect)) = crate::chartview::selected_rotate(app, geo, sh, p) + { + app.grid.drag = Drag::Rotate { obj, rect, stepped: false }; + return; + } // The selected object's handles reach a little outside it, so they win over hit-testing. // Only they resize: a press anywhere on another object selects and moves it, as the // hover cursor shows. @@ -157,6 +164,20 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo } return; } + // A corner of the selected chart's values outline drags the block the chart plots + // (#4389); a click on it keeps the chart selected. + if let Some(p) = at + && app.editor.is_none() + && let Some((chart, orig, corner)) = crate::chartview::chart_data_handle(app, geo, sh, p) + { + if primary_drag { + app.grid.drag = Drag::ChartData { chart, orig, corner, to: None }; + if let Some(now) = pos { + drag_chart_data(app, geo, sh, now); + } + } + return; + } app.selected_object = None; } // A right-click on a chart, picture, shape, slicer or form control opens the object's menu, not @@ -630,22 +651,30 @@ fn handle_context_menu_and_keyboard(app: &mut SheetApp, input: &InteractionInput keyboard(app, &ctx, resp, geo, sh); } +/// Whether Esc was pressed this frame, with any modifiers; every Esc press is then spent, so the +/// grid's own Esc doesn't also drop a pending copy or Format Painter. +fn spend_escape(ctx: &egui::Context) -> bool { + ctx.input_mut(|i| { + let pressed = i.key_pressed(egui::Key::Escape); + if pressed { + i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })); + } + pressed + }) +} + fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) { let (geo, sh, wb, sel, pos) = (input.geo, input.sheet, input.workbook, &input.selection, input.position); let resp = input.response; // Esc during a header-boundary drag cancels it: undo the preview, ignore the release. egui // aborts the drag on Esc, so `resp.dragged()` is already false in this frame. The key is // spent on the drag, so the grid's Esc doesn't also drop a pending copy or Format Painter. - if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) - && input.context.input_mut(|i| { - let pressed = i.key_pressed(egui::Key::Escape); - if pressed { - // With any modifiers, as before: the drag is cancelled and every Esc press spent. - i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })); - } - pressed - }) - { + // Esc during a drag of a chart's values outline drops it: the chart keeps its data, whatever + // modifiers are held (egui ends the drag on any Esc, so the release must not apply it). + if matches!(app.grid.drag, Drag::ChartData { .. }) && spend_escape(&input.context) { + app.grid.drag = Drag::None; + } + if matches!(app.grid.drag, Drag::ResizeCol { .. } | Drag::ResizeRow { .. }) && spend_escape(&input.context) { // Undo back to where the drag began, but never past it into an earlier edit. let steps = resize_steps(app); if steps > 0 { @@ -742,6 +771,11 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) { scroll_by(app, auto); } Drag::Object { .. } => drag_object(app, geo, sh, p), + Drag::Rotate { obj, rect, .. } => rotate_object(app, obj, rect, p, input.modifiers.shift), + Drag::ChartData { .. } => { + drag_chart_data(app, geo, sh, p); + scroll_by(app, auto); + } Drag::None => {} } } @@ -822,6 +856,23 @@ fn handle_release(app: &mut SheetApp, input: &InteractionInput<'_>) { coalesce_resize_undo(app); } } + // The release may be the first frame to report the pointer's last position, so the + // block is taken from there. (Esc already dropped a cancelled drag, and so did a + // change to the chart's data; one in the release's own frame is caught here.) + Drag::ChartData { chart, orig, corner, to } => { + let to = if resp.drag_stopped() + && let Some(p) = pos + { + Some(chart_data_target(geo, sh, orig, corner, p)) + } else { + to + }; + if let Some(to) = to.filter(|to| *to != orig) + && chart_still_plots(app, chart, orig) + { + app.run_or_alert("chart.setValuesRange", json!({"chart": chart, "range": to.a1()})); + } + } Drag::MoveCols { source, before: Some(before) } => { if let Err(e) = app.run("sheet.moveColumns", json!({"cols": source.a1(), "before": before})) { app.message = Some(("GridCraft".into(), crate::clean_error(&e))); @@ -1159,6 +1210,52 @@ pub(super) fn hidden_row_edge(geo: &Geo, sh: &Sheet, y: f32) -> Option { row_edge(geo, sh, y).map(|(r, _)| r).filter(|&r| sh.row_height(r) <= 0.0) } +/// Arrow-key nudge of a selected object, sheet points (Ctrl/Alt: fine). +const NUDGE: f32 = 6.0; + +/// Arrow keys aimed at the selected object rather than the cells: they nudge it. +pub(super) fn object_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> bool { + use egui::Key; + let Some(o) = app.selected_object else { return false }; + let step = if m.ctrl || m.alt { 1.0 } else { NUDGE }; + // Arrows follow the screen: a right-to-left sheet is mirrored. + let sx = if sh.right_to_left { -step } else { step }; + let d = match key { + Key::ArrowLeft => vec2(-sx, 0.0), + Key::ArrowRight => vec2(sx, 0.0), + Key::ArrowUp => vec2(0.0, -step), + Key::ArrowDown => vec2(0.0, step), + _ => return false, + }; + // On Windows and Linux egui sets `command` with `ctrl`: only the Mac Command key opts out. + if m.shift || m.mac_cmd { + return false; + } + let Some(a) = sh.object_anchor(o) else { return false }; + let x0 = (sh.col_left(a.cell.col) as f32 + a.dx + d.x).max(0.0); + let y0 = (sh.row_top(a.cell.row) as f32 + a.dy + d.y).max(0.0); + let nc = CellRef::new(sh.row_at(f64::from(y0)), sh.col_at(f64::from(x0))); + let params = + json!({"kind": o.kind.name(), "id": o.id, "at": nc.a1(), "dx": x0 - sh.col_left(nc.col) as f32, "dy": y0 - sh.row_top(nc.row) as f32}); + app.run_or_alert("object.move", params); + true +} + +/// Turns the dragged shape so its rotation handle points at `p`; the drag is one undo step. +fn rotate_object(app: &mut SheetApp, obj: ObjRef, rect: Rect, p: Pos2, snap: bool) { + let deg = crate::frame::angle_to(rect, p, snap); + let revision = app.session.active().map(|d| d.revision); + let _ = app.session.run("object.move", json!({"kind": obj.kind.name(), "id": obj.id, "rotation": deg})); + let Drag::Rotate { stepped, .. } = app.grid.drag else { return }; + if stepped { + coalesce_last_undo(app); + } else if app.session.active().map(|d| d.revision) != revision + && let Drag::Rotate { stepped, .. } = &mut app.grid.drag + { + *stepped = true; + } +} + /// Moves the dragged object, or resizes it from the grabbed handle, to follow the pointer at `p` /// (logical coordinates). The whole drag coalesces into one undo step of its own. fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) { @@ -1167,7 +1264,16 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) { let (cell, dx, dy, w, h) = orig; let x0 = sh.col_left(cell.col) as f32 + dx; let y0 = sh.row_top(cell.row) as f32 + dy; + let frame_deg = crate::chartview::frame_of(sh, obj).0; let [x0, y0, x1, y1] = match handle { + Some(hd) if frame_deg != 0.0 => { + let fh = crate::frame::Handle { x: hd.sides().0, y: hd.sides().1 }; + let r0 = Rect::from_min_max(pos2(x0, y0), pos2(x0 + w, y0 + h)); + let min = crate::objects::min_size(sh, obj); + let r = crate::frame::resized_turned_by_min(r0, frame_deg, fh, d, min, false); + let (nx, ny) = (r.min.x.max(0.0), r.min.y.max(0.0)); + [nx, ny, r.max.x.max(nx + min.x), r.max.y.max(ny + min.y)] + } Some(hd) => crate::objects::resized([x0, y0, x0 + w, y0 + h], hd, d, crate::objects::min_size(sh, obj)), None => { let (x0, y0) = ((x0 + d.x).max(0.0), (y0 + d.y).max(0.0)); @@ -1201,6 +1307,69 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) { } } +/// Previews the selected chart's values block with the grabbed corner dragged to `p` (logical +/// coordinates); the opposite corner stays. The release gives the chart the block +/// (`chart.setValuesRange`). +fn drag_chart_data(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) { + let Drag::ChartData { chart, orig, corner, .. } = app.grid.drag else { return }; + // The chart's data changed under the drag: drop it, as Esc does, rather than preview a + // block the release would put over that change. + if !chart_still_plots(app, chart, orig) { + app.grid.drag = Drag::None; + return; + } + app.grid.drag = Drag::ChartData { chart, orig, corner, to: Some(chart_data_target(geo, sh, orig, corner, p)) }; +} + +/// Whether chart `chart` on the active sheet still plots the values block `orig` its drag +/// started from. A command run between frames (the control channel, a macro) may have changed +/// or removed it, and the dragged block would then overwrite that change. Read from the session, +/// not the frame's workbook, which predates such a command. +fn chart_still_plots(app: &SheetApp, chart: u32, orig: RangeRef) -> bool { + let Some(wb) = app.session.active().map(|d| &d.wb) else { return false }; + let si = wb.active_sheet(); + wb.sheet(si) + .and_then(|sh| sh.charts.iter().find(|ch| ch.id == chart)) + .and_then(|ch| gridcraft_engine::chart_data::chart_data(wb, si, ch)) + .is_some_and(|data| data.sheet == si && data.values == orig) +} + +/// The values block `orig` with its `corner` dragged to `p`. Each edge the corner moves snaps +/// to the gridline nearest the pointer, so every row and column changes over at its own middle +/// whatever its height or width, and a release where the press was (on the corner's own +/// gridlines) changes nothing. The block may flip past its fixed edges, as a selection does; a +/// moving edge dropped on its fixed edge keeps one row or column. +fn chart_data_target(geo: &Geo, sh: &Sheet, orig: RangeRef, corner: crate::objects::Handle, p: Pos2) -> RangeRef { + let (sx, sy) = corner.sides(); + let (x, y) = (p.x.clamp(geo.cells.left() + 1.0, geo.cells.right() - 1.0), p.y.clamp(geo.cells.top() + 1.0, geo.cells.bottom() - 1.0)); + // Gridline `k` is the top (left) edge of row (column) `k`; the last one closes the sheet. + let row = geo.row_at(sh, y); + let row_line = nearest_line(geo.y(sh, row), sh.row_height(row) * geo.z, row, y, MAX_ROWS); + let col = geo.col_at(sh, x); + let col_line = nearest_line(geo.x(sh, col), sh.col_width(col) * geo.z, col, x, MAX_COLS); + let (r0, r1) = between_lines(if sy < 0 { orig.end.row.saturating_add(1) } else { orig.start.row }, row_line, sy); + let (c0, c1) = between_lines(if sx < 0 { orig.end.col.saturating_add(1) } else { orig.start.col }, col_line, sx); + RangeRef::new(CellRef::new(r0, c0), CellRef::new(r1, c1)) +} + +/// The gridline nearest `v` for line `index`, which starts at `start` and is `size` long: its +/// own start, or the next line's past its middle (never past `last`). +fn nearest_line(start: f32, size: f32, index: u32, v: f32, last: u32) -> u32 { + if v - start < size / 2.0 { index } else { index.saturating_add(1).min(last) } +} + +/// The rows (columns) from gridline `fixed` to gridline `moving`. A moving edge on the fixed one +/// keeps one line on its own side: after it for a bottom or right edge (`dir` > 0), before it +/// for a top or left edge. +fn between_lines(fixed: u32, moving: u32, dir: i8) -> (u32, u32) { + let moving = match (moving == fixed, dir > 0) { + (false, _) => moving, + (true, true) => fixed.saturating_add(1), + (true, false) => fixed.saturating_sub(1), + }; + (fixed.min(moving), fixed.max(moving).saturating_sub(1)) +} + /// A click on a hyperlink. References select; web and e-mail addresses ask first (the dialog's /// OK calls `Session::open_confirmed_link`, since `link.open` refuses them for programmatic /// callers, #2181); every other kind is refused with a message. The decision is the engine's @@ -1253,6 +1422,28 @@ pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, exte mod resize_tests { use super::*; + #[test] + fn a_chart_data_edge_snaps_to_the_nearest_gridline_of_any_size() { + // Row 5 starts at 100 and is 20 tall: before its middle the line is its own, past it the next. + assert_eq!(nearest_line(100.0, 20.0, 5, 109.0, MAX_ROWS), 5); + assert_eq!(nearest_line(100.0, 20.0, 5, 111.0, MAX_ROWS), 6); + // A 100-tall row changes over at 50 into it, not at the grabbed row's middle. + assert_eq!(nearest_line(100.0, 100.0, 5, 149.0, MAX_ROWS), 5); + assert_eq!(nearest_line(100.0, 100.0, 5, 151.0, MAX_ROWS), 6); + assert_eq!(nearest_line(0.0, 20.0, MAX_ROWS - 1, 19.0, MAX_ROWS), MAX_ROWS); + // A1:A5 (lines 0 and 5) by its bottom edge: on line 5 it stays, on 8 it grows, on 2 it shrinks. + assert_eq!(between_lines(0, 5, 1), (0, 4)); + assert_eq!(between_lines(0, 8, 1), (0, 7)); + assert_eq!(between_lines(0, 2, 1), (0, 1)); + // Dropped on its fixed edge it keeps one row; past it the block flips. + assert_eq!(between_lines(4, 4, 1), (4, 4)); + assert_eq!(between_lines(4, 2, 1), (2, 3)); + // By its top edge (fixed line 5, below A5). + assert_eq!(between_lines(5, 0, -1), (0, 4)); + assert_eq!(between_lines(5, 5, -1), (4, 4)); + assert_eq!(between_lines(5, 7, -1), (5, 6)); + } + #[test] fn resize_targets_follow_the_selection_only_when_the_dragged_line_is_in_it() { let sel = [RangeRef::cols(0, 0), RangeRef::cols(2, 3)]; diff --git a/crates/ui-egui/src/grid/keyboard.rs b/crates/ui-egui/src/grid/keyboard.rs index 89259ca86f..35cc4404ac 100644 --- a/crates/ui-egui/src/grid/keyboard.rs +++ b/crates/ui-egui/src/grid/keyboard.rs @@ -1,4 +1,5 @@ use super::geo::Geo; +use super::interact::object_key; use super::menus::is_checkbox; use super::{CellRef, Drag, Sheet, SheetApp, json}; @@ -81,8 +82,9 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res } egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => { use egui::Key; - if crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) { - shortcut_ran = true; + let nudged = object_key(app, sh, key, m); + if nudged || crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) { + shortcut_ran |= !nudged; continue; } let cmd = m.command; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3086d1fc98..65cca4d58a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -36,6 +36,7 @@ pub mod fonts; pub mod form_controls; pub mod formula_bar; mod formula_locale; +pub mod frame; pub mod function_library; pub mod grid; pub mod i18n; diff --git a/crates/ui-egui/tests/it/chart_data_drag.rs b/crates/ui-egui/tests/it/chart_data_drag.rs new file mode 100644 index 0000000000..3c2066e33a --- /dev/null +++ b/crates/ui-egui/tests/it/chart_data_drag.rs @@ -0,0 +1,265 @@ +//! #4389 and #4390: a selected chart outlines its data in the sheet (series names red, category +//! labels purple, values blue), and dragging a corner of the values outline changes what the +//! chart plots, through real pointer input. + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Shape, vec2}; +use gridcraft_engine::core::RangeRef; +use gridcraft_ui_egui::theme::Tokens; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, gridcraft_ui_egui::SheetApp>; + +/// 10..50 down A1:A5 and 5s below them, charted from A1:A5, which stays the cell selection as +/// after Insert › Chart, so the fill handle sits on the outline's bottom-right corner. +fn fixture() -> (Harness, u32) { + let mut session = crate::support::blank_session(); + let values: Vec<_> = [10, 20, 30, 40, 50, 5, 5, 5].iter().map(|v| json!([v])).collect(); + session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + session.execute("selection.set", json!({"range": "A1:A5"})).unwrap(); + let chart = session.execute("insert.chart", json!({"type": "column", "at": "D3", "width": 300, "height": 200})).unwrap(); + let id = chart["chart"].as_u64().unwrap() as u32; + let mut h = crate::support::stepped_harness(session); + h.state_mut().select_object_id(Some(id)); + h.run_steps(2); + (h, id) +} + +fn values(h: &Harness) -> String { + h.state().session.doc().unwrap().wb.active().unwrap().charts[0].series[0].values.clone() +} + +/// On-screen rect of `range`. +fn rect(h: &Harness, range: &str) -> egui::Rect { + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + app.grid.geo.as_ref().unwrap().range_rect(sh, RangeRef::parse(range).unwrap()) +} + +fn hover(h: &mut Harness, at: Pos2) { + h.input_mut().events.push(Event::PointerMoved(at)); + h.run_steps(2); +} + +fn button(h: &mut Harness, at: Pos2, pressed: bool) { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// Presses at `from` and moves to `to` in small steps, leaving the button down. +fn press_and_move(h: &mut Harness, from: Pos2, to: Pos2) { + hover(h, from); + button(h, from, true); + press_and_move_on(h, from, to); +} + +/// With the button already down, moves from `from` to `to` in small steps. +fn press_and_move_on(h: &mut Harness, from: Pos2, to: Pos2) { + for i in 1..=8 { + h.input_mut().events.push(Event::PointerMoved(from + (to - from) * (i as f32 / 8.0))); + h.run_steps(1); + } +} + +#[test] +fn dragging_the_values_corner_extends_the_chart_data() { + let (mut h, id) = fixture(); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); + let corner = rect(&h, "A1:A5").right_bottom(); + hover(&mut h, corner); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::ResizeNwSe, "the corner shows a resize cursor, not the fill cross"); + // Three rows down from the corner, as the hand moves it. + let target = rect(&h, "A8").right_bottom(); + press_and_move(&mut h, corner, target); + // The outline previews the new block while the button is held; the chart is unchanged. + let blue = Tokens::get(&h.ctx).ref_color(0, true); + let preview = rect(&h, "A1:A8"); + let previewed = h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == preview && r.stroke.color == blue)); + assert!(previewed, "the outline follows the pointer"); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$8", "the chart plots the dragged block"); + assert_eq!(h.state().selected_chart(), Some(id), "the chart stays selected"); + let a6 = h.state().session.doc().unwrap().wb.active().unwrap().value(gridcraft_engine::core::CellRef::parse("A6").unwrap()); + assert_eq!(a6, gridcraft_engine::core::Value::number(5.0), "the press did not drag the fill handle"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "one undo step puts the block back"); +} + +#[test] +fn dragging_the_top_corner_down_shrinks_the_chart_data() { + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").left_top() + vec2(1.0, 1.0); + let target = rect(&h, "A3").left_top() + vec2(1.0, 1.0); + press_and_move(&mut h, corner, target); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$3:$A$5"); +} + +/// #4391 review: a corner lies on the boundary of the next row and column, so reading the pointer +/// as is put a press on the bottom-right corner of A1:A5 in B6. +#[test] +fn a_drag_back_to_the_grabbed_corner_or_along_its_edge_keeps_the_other_axis() { + // Away and back to the very point pressed: nothing changes. + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").right_bottom(); + press_and_move(&mut h, corner, corner + vec2(40.0, 30.0)); + press_and_move_on(&mut h, corner + vec2(40.0, 30.0), corner); + button(&mut h, corner, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5", "a release where the press was leaves the data alone"); + // Straight down the right edge of column A: rows only, no column B. + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").right_bottom(); + let target = rect(&h, "A6").right_bottom(); + press_and_move(&mut h, corner, target); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$6"); +} + +/// #4391 review: the drag read the pointer from the middle of the grabbed row, so with a tall +/// row 5 the pointer could reach the bottom of a short row 6 and the block stayed at A1:A5. +#[test] +fn a_drag_past_rows_of_unequal_height_follows_the_rows_under_the_pointer() { + let (mut h, _) = fixture(); + h.state_mut().run("home.rowHeight", json!({"rows": "5:5", "height": 120})).unwrap(); + h.run_steps(2); + let corner = rect(&h, "A1:A5").right_bottom(); + let row6 = rect(&h, "A6"); + assert!(rect(&h, "A5").height() > 3.0 * row6.height(), "row 5 is much taller than row 6"); + // Short of the middle of row 6 the edge stays on row 5's bottom gridline. + let short = corner + vec2(0.0, row6.height() * 0.4); + press_and_move(&mut h, corner, short); + assert!(values_outline_at(&h, "A1:A5")); + // At the bottom of row 6 the block takes row 6, in the preview and on release. + let target = row6.right_bottom(); + press_and_move_on(&mut h, short, target); + assert!(values_outline_at(&h, "A1:A6"), "the preview takes row 6"); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$6"); +} + +#[test] +fn escape_cancels_a_values_drag() { + let (mut h, _) = fixture(); + let corner = rect(&h, "A1:A5").right_bottom(); + let target = rect(&h, "A8").right_bottom(); + press_and_move(&mut h, corner, target); + h.key_press(Key::Escape); + h.run_steps(2); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); +} + +/// Whether the last frame stroked `range` in the values blue. +fn values_outline_at(h: &Harness, range: &str) -> bool { + let blue = Tokens::get(&h.ctx).ref_color(0, true); + let want = rect(h, range); + h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == blue)) +} + +#[test] +fn a_release_in_the_same_frame_as_the_last_move_takes_the_release_position() { + let (mut h, _) = fixture(); + let (corner, a6, end) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A6").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, a6); + // The pointer reaches A8 and the button goes up within one frame. + h.input_mut().events.push(Event::PointerMoved(end)); + h.input_mut().events.push(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(values(&h), "Sheet1!$A$1:$A$8"); +} + +/// A command that changes the chart's data while the button is held (the control channel runs +/// between frames) makes the drag stale: releasing must not put the dragged block over it, +/// whether the pointer moves on first or is released straight away. +#[test] +fn a_chart_data_change_during_the_drag_is_not_overwritten_by_the_release() { + for move_on in [true, false] { + let (mut h, id) = fixture(); + let (corner, a7, a8) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A7").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, a7); + h.state_mut().session.execute("chart.setValuesRange", json!({"chart": id, "range": "A2:A4"})).unwrap(); + if move_on { + press_and_move_on(&mut h, a7, a8); + } + button(&mut h, if move_on { a8 } else { a7 }, false); + assert_eq!(values(&h), "Sheet1!$A$2:$A$4", "the newer data stays (pointer moved on: {move_on})"); + assert!(!values_outline_at(&h, "A1:A8") && !values_outline_at(&h, "A1:A7"), "no stale preview is left (pointer moved on: {move_on})"); + } +} + +#[test] +fn escape_with_ctrl_held_still_cancels_a_values_drag() { + let (mut h, _) = fixture(); + let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, target); + h.input_mut().events.push(Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::CTRL }); + h.run_steps(2); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$5"); +} + +#[test] +fn the_preview_stays_while_the_drag_scrolls_the_chart_away() { + let (mut h, _) = fixture(); + // Column A stays in a frozen pane while the chart in D:H scrolls off to the left. + h.state_mut().run("view.freezePanes", json!({"cell": "B1"})).unwrap(); + h.run_steps(2); + let (corner, target) = (rect(&h, "A1:A5").right_bottom(), rect(&h, "A8").right_bottom()); + press_and_move(&mut h, corner, target); + assert!(values_outline_at(&h, "A1:A8")); + h.state_mut().view_mut().unwrap().scroll.x = 3000.0; + h.run_steps(2); + assert!(values_outline_at(&h, "A1:A8"), "the dragged block is still previewed"); + button(&mut h, target, false); + assert_eq!(values(&h), "Sheet1!$A$1:$A$8"); +} + +#[test] +fn a_corner_hidden_under_frozen_rows_cannot_be_grabbed() { + let mut session = crate::support::blank_session(); + let values: Vec<_> = (1..=12).map(|v| json!([v])).collect(); + session.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + session.execute("selection.set", json!({"range": "A5:A8"})).unwrap(); + let chart = session.execute("insert.chart", json!({"type": "column", "at": "D2", "width": 300, "height": 200})).unwrap(); + session.execute("view.freezePanes", json!({"cell": "A4"})).unwrap(); + let mut h = crate::support::stepped_harness(session); + h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32)); + // Scroll two rows, so the top of row 5 lies under the frozen rows 1-3. + let two_rows = { + let sh = h.state().session.doc().unwrap().wb.active().unwrap().clone(); + (sh.row_top(5) - sh.row_top(3)) as f32 + }; + h.state_mut().view_mut().unwrap().scroll.y = two_rows; + h.run_steps(2); + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + let geo = app.grid.geo.as_ref().unwrap(); + let block = geo.range_rect(sh, RangeRef::parse("A5:A8").unwrap()); + let hidden = block.left_top(); + let frozen_bottom = geo.y(sh, 2) + sh.row_height(2) as f32 * geo.z; + assert!(geo.cells.contains(hidden) && hidden.y + 4.0 < frozen_bottom, "the top corner lies over the frozen rows: {hidden:?} {frozen_bottom}"); + assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, hidden).is_none(), "a hidden corner is not a handle"); + assert!(gridcraft_ui_egui::chartview::chart_data_handle(app, geo, sh, block.right_bottom()).is_some(), "a visible corner still is"); +} + +#[test] +fn a_selected_chart_outlines_names_categories_and_values_in_their_colours() { + let mut session = crate::support::blank_session(); + session + .execute("range.setValues", json!({"range": "A1", "values": [["", "North", "South"], ["Q1", 10, 15], ["Q2", 20, 25], ["Q3", 30, 35]]})) + .unwrap(); + session.execute("selection.set", json!({"range": "A1:C4"})).unwrap(); + let chart = session.execute("insert.chart", json!({"type": "column", "at": "F2", "width": 300, "height": 200})).unwrap(); + let mut h = crate::support::stepped_harness(session); + h.state_mut().select_object_id(Some(chart["chart"].as_u64().unwrap() as u32)); + h.run_steps(2); + let t = Tokens::get(&h.ctx); + let stroked = |h: &Harness, range: &str, color: egui::Color32| { + let want = rect(h, range); + h.output().shapes.iter().any(|s| matches!(&s.shape, Shape::Rect(r) if r.rect == want && r.stroke.color == color && r.stroke.width == 1.5)) + }; + assert!(stroked(&h, "B1:C1", t.ref_color(1, true)), "series names in red"); + assert!(stroked(&h, "A2:A4", t.ref_color(2, true)), "category labels in purple"); + assert!(stroked(&h, "B2:C4", t.ref_color(0, true)), "the values as one blue block"); + assert!(!stroked(&h, "B2:B4", t.ref_color(0, true)), "not one outline per series"); +} diff --git a/crates/ui-egui/tests/it/interaction.rs b/crates/ui-egui/tests/it/interaction.rs index 7d09bff839..71bdd6ae54 100644 --- a/crates/ui-egui/tests/it/interaction.rs +++ b/crates/ui-egui/tests/it/interaction.rs @@ -336,6 +336,77 @@ fn arrows_escape_and_undo() { assert_eq!(value(&h, "B2"), Value::Empty); } +#[test] +fn undo_and_redo_reach_the_sheet_while_find_and_replace_is_open() { + let mut h = harness(blank()); + for t in ["x1", "x2"] { + text(&mut h, t); + key(&mut h, Key::Enter, Modifiers::NONE); + } + h.state_mut().open_dialog("find", json!({"replace": true})); + h.run_steps(3); + if let Some(d) = h.state_mut().dialog.as_mut() { + d.values.insert("what".into(), json!("x")); + d.values.insert("with".into(), json!("y")); + } + h.run_steps(2); + h.get_by_label("Replace All").click(); + h.run_steps(3); + assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2"))); + // Keyboard focus on a button must not reserve Undo/Redo for text editing. + h.get_by_label("Replace All").focus(); + h.run_steps(2); + assert!(h.ctx.egui_wants_keyboard_input()); + assert!(!h.ctx.text_edit_focused()); + key(&mut h, Key::Z, Modifiers::COMMAND); + assert!(h.state().dialog.is_some(), "the dialog stays open"); + assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("x1"), Value::from("x2")), "one Undo takes back the whole Replace All"); + key(&mut h, Key::Y, Modifiers::COMMAND); + assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2"))); + // The Mac Redo shortcut works too, as it does on the sheet. + key(&mut h, Key::Z, Modifiers::COMMAND); + assert_eq!(value(&h, "A1"), Value::from("x1")); + key(&mut h, Key::Z, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2"))); + assert!(h.state().dialog.is_some(), "the dialog is still open"); + h.get_by_label("Find what:").focus(); + h.run_steps(2); + assert!(h.ctx.text_edit_focused()); + let before = h.state().dialog.as_ref().unwrap().values.get("what").cloned(); + h.input_mut().events.push(Event::Text("extra".into())); + h.run_steps(2); + assert_ne!(h.state().dialog.as_ref().unwrap().values.get("what"), before.as_ref()); + key(&mut h, Key::Z, Modifiers::COMMAND); + assert_eq!(h.state().dialog.as_ref().unwrap().values.get("what"), before.as_ref(), "Undo restores the Find field"); + assert_eq!((value(&h, "A1"), value(&h, "A2")), (Value::from("y1"), Value::from("y2")), "text-field Undo leaves the sheet alone"); +} + +#[test] +fn find_message_blocks_workbook_undo_and_redo() { + let mut session = blank(); + session.execute("cell.set", json!({"cell": "A1", "input": "first"})).unwrap(); + session.execute("cell.set", json!({"cell": "A1", "input": "second"})).unwrap(); + session.execute("edit.undo", json!({})).unwrap(); + let mut h = harness(session); + h.state_mut().open_dialog("find", json!({"replace": true})); + h.run_steps(3); + // An empty search raises the real modal error over Find and Replace. + h.get_by_label("Replace All").click(); + h.run_steps(3); + assert!(h.state().message.is_some()); + assert!(!h.ctx.text_edit_focused()); + for (key_code, modifiers) in [(Key::Z, Modifiers::COMMAND), (Key::Y, Modifiers::COMMAND), (Key::Z, Modifiers::COMMAND | Modifiers::SHIFT)] { + key(&mut h, key_code, modifiers); + assert_eq!(value(&h, "A1"), Value::from("first"), "the message blocks workbook shortcuts"); + assert!(h.state().message.is_some()); + } + h.state_mut().message = None; + h.run_steps(2); + h.get_by_label("Replace All").focus(); + h.run_steps(2); + key(&mut h, Key::Y, Modifiers::COMMAND); + assert_eq!(value(&h, "A1"), Value::from("second"), "Redo works again after dismissing the message"); +} #[test] fn shift_arrows_in_point_mode_extend_from_the_pointed_cell() { let mut s = blank(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ad4d67c4ca..83f4b57362 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -16,6 +16,7 @@ mod cell_editor_caret; mod cell_pictures; mod cf_rule_pick; mod cf_rules_manager; +mod chart_data_drag; mod chart_data_table; mod chart_resize; mod chart_source_layering; diff --git a/crates/ui-egui/tests/shape_select.rs b/crates/ui-egui/tests/shape_select.rs new file mode 100644 index 0000000000..a3d6745726 --- /dev/null +++ b/crates/ui-egui/tests/shape_select.rs @@ -0,0 +1,305 @@ +//! Selecting, moving and resizing an inserted shape through real pointer input. + +use egui::{Event, Modifiers, PointerButton, vec2}; +use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_engine::model::Anchor; +use gridcraft_ui_egui::{SheetApp, grid::Geo}; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +fn fixture() -> (Harness, u32) { + fixture_of("rectangle") +} + +fn fixture_of(kind: &str) -> (Harness, u32) { + let mut session = Session::new(); + session.new_workbook(); + let id = if kind == "ink" { + session.execute("draw.stroke", json!({"points": [[300, 100], [420, 200]]})).unwrap(); + let sh = session.doc().unwrap().wb.active().unwrap(); + sh.shapes.iter().find(|s| s.kind == gridcraft_engine::model::ShapeKind::Ink).unwrap().id + } else { + let height = if matches!(kind, "line" | "arrow") { 0 } else { 100 }; + let shape = session.execute("insert.shape", json!({"kind": kind, "at": "D3", "width": 160, "height": height})).unwrap(); + shape["shape"].as_u64().unwrap() as u32 + }; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h.state_mut().selected_object = None; + h.run_steps(2); + (h, id) +} + +fn anchor(h: &Harness, id: u32) -> Anchor { + h.state().session.doc().unwrap().wb.active().unwrap().shapes.iter().find(|s| s.id == id).unwrap().anchor +} + +fn rect(h: &Harness, id: u32) -> egui::Rect { + let app = h.state(); + let sh = app.session.doc().unwrap().wb.active().unwrap(); + let geo = Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll); + let a = anchor(h, id); + let min = geo.cell_rect(sh, a.cell).min + vec2(a.dx, a.dy) * geo.z; + egui::Rect::from_min_size(min, vec2(a.width, a.height) * geo.z) +} + +fn button(h: &mut Harness, pos: egui::Pos2, pressed: bool) { + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) { + h.input_mut().events.push(Event::PointerMoved(from)); + h.run_steps(2); + button(h, from, true); + h.input_mut().events.push(Event::PointerMoved(to)); + h.run_steps(3); + button(h, to, false); +} + +#[test] +fn clicking_a_shape_selects_it() { + let (mut h, id) = fixture(); + let c = rect(&h, id).center(); + h.input_mut().events.push(Event::PointerMoved(c)); + h.run_steps(2); + button(&mut h, c, true); + button(&mut h, c, false); + assert_eq!(h.state().selected_object.map(|o| o.id), Some(id)); + assert_eq!(h.state().session.active().unwrap().selection.current().start, CellRef::parse("A1").unwrap()); +} + +fn handle_at(h: &Harness, at: egui::Pos2) -> bool { + h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Circle(k) if (k.center - at).length() < 1.0 && k.radius == 4.0)) +} + +#[test] +fn a_selected_shape_shows_its_handles() { + let (mut h, id) = fixture(); + let r = rect(&h, id); + assert!(!handle_at(&h, r.center_top()), "no handles before selecting"); + h.input_mut().events.push(Event::PointerMoved(r.center())); + h.run_steps(2); + button(&mut h, r.center(), true); + button(&mut h, r.center(), false); + for at in [r.left_top(), r.center_top(), r.right_bottom()] { + assert!(handle_at(&h, at), "handle at {at:?}"); + } +} + +#[test] +fn dragging_a_shape_moves_it() { + let (mut h, id) = fixture(); + let before = rect(&h, id); + drag(&mut h, before.center(), before.center() + vec2(120.0, 80.0)); + let after = rect(&h, id); + assert!((after.min - before.min - vec2(120.0, 80.0)).length() < 4.0, "moved from {before:?} to {after:?}"); + assert_eq!(after.size(), before.size()); +} + +fn select(h: &mut Harness, id: u32) { + let c = rect(h, id).center(); + select_at(h, c); +} + +fn select_at(h: &mut Harness, c: egui::Pos2) { + h.input_mut().events.push(Event::PointerMoved(c)); + h.run_steps(2); + button(h, c, true); + button(h, c, false); +} + +#[test] +fn every_handle_shows_its_resize_cursor() { + let (mut h, id) = fixture(); + select(&mut h, id); + let r = rect(&h, id); + for (at, cursor) in [ + (r.left_top(), egui::CursorIcon::ResizeNwSe), + (r.right_top(), egui::CursorIcon::ResizeNeSw), + (r.left_center(), egui::CursorIcon::ResizeHorizontal), + (r.center_bottom(), egui::CursorIcon::ResizeVertical), + ] { + h.input_mut().events.push(Event::PointerMoved(at)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, cursor, "at {at:?}"); + } +} + +#[test] +fn dragging_the_left_handle_moves_only_the_left_edge() { + let (mut h, id) = fixture(); + select(&mut h, id); + let before = rect(&h, id); + drag(&mut h, before.left_center(), before.left_center() + vec2(-50.0, 40.0)); + let after = rect(&h, id); + assert!((after.left() - (before.left() - 50.0)).abs() < 2.0, "{before:?} -> {after:?}"); + assert!((after.right() - before.right()).abs() < 2.0, "{before:?} -> {after:?}"); + assert!((after.top() - before.top()).abs() < 2.0 && (after.bottom() - before.bottom()).abs() < 2.0, "{before:?} -> {after:?}"); +} + +#[test] +fn dragging_the_top_left_handle_keeps_the_bottom_right_corner() { + let (mut h, id) = fixture(); + select(&mut h, id); + let before = rect(&h, id); + drag(&mut h, before.left_top(), before.left_top() + vec2(30.0, 20.0)); + let after = rect(&h, id); + assert!((after.right_bottom() - before.right_bottom()).length() < 2.0, "{before:?} -> {after:?}"); + assert!((after.left_top() - before.left_top() - vec2(30.0, 20.0)).length() < 2.0, "{before:?} -> {after:?}"); +} + +#[test] +fn dragging_the_corner_resizes_a_shape() { + let (mut h, id) = fixture(); + select(&mut h, id); + let before = rect(&h, id); + drag(&mut h, before.right_bottom(), before.right_bottom() + vec2(60.0, 30.0)); + let after = rect(&h, id); + assert!(after.width() > before.width() + 40.0 && after.height() > before.height() + 20.0, "{before:?} -> {after:?}"); +} + +fn rotation(h: &Harness, id: u32) -> f32 { + h.state().session.doc().unwrap().wb.active().unwrap().shapes.iter().find(|s| s.id == id).unwrap().rotation +} + +#[test] +fn dragging_the_rotation_handle_turns_the_shape() { + let (mut h, id) = fixture(); + select(&mut h, id); + let r = rect(&h, id); + let knob = gridcraft_ui_egui::frame::rotate_handle(r, 0.0); + assert!(handle_at(&h, knob), "the rotation handle shows"); + h.input_mut().events.push(Event::PointerMoved(knob)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Crosshair); + drag(&mut h, knob, r.center() + vec2(200.0, 0.0)); + assert_eq!(rotation(&h, id), 90.0); + assert_eq!(rect(&h, id), r, "turning keeps the box"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(rotation(&h, id), 0.0, "one drag is one undo step"); +} + +#[test] +fn a_turned_shape_is_hit_inside_its_turned_outline() { + let (mut h, id) = fixture(); + h.state_mut().run("object.move", json!({"kind": "shape", "id": id, "rotation": 90})).unwrap(); + h.run_steps(2); + let r = rect(&h, id); + // Turned 90°, the shape reaches half its width above and below its centre. + let below = r.center() + vec2(0.0, r.width() / 2.0 - 5.0); + assert!(!r.contains(below)); + h.input_mut().events.push(Event::PointerMoved(below)); + h.run_steps(2); + button(&mut h, below, true); + button(&mut h, below, false); + assert_eq!(h.state().selected_object.map(|o| o.id), Some(id)); +} + +fn key(h: &mut Harness, key: egui::Key, modifiers: Modifiers) { + h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + h.run_steps(2); +} + +#[test] +fn arrow_keys_nudge_the_selected_shape_not_the_cell_cursor() { + let (mut h, id) = fixture(); + select(&mut h, id); + let before = anchor(&h, id); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + key(&mut h, egui::Key::ArrowDown, Modifiers { ctrl: true, command: true, ..Default::default() }); + let after = anchor(&h, id); + let x = |a: &Anchor| h.state().session.doc().unwrap().wb.active().unwrap().col_left(a.cell.col) as f32 + a.dx; + let y = |a: &Anchor| h.state().session.doc().unwrap().wb.active().unwrap().row_top(a.cell.row) as f32 + a.dy; + assert!((x(&after) - x(&before) - 6.0).abs() < 0.01 && (y(&after) - y(&before) - 1.0).abs() < 0.01, "{before:?} -> {after:?}"); + assert_eq!(h.state().session.active().unwrap().selection.current().start, CellRef::parse("A1").unwrap()); +} + +#[test] +fn escape_deselects_the_shape() { + let (mut h, id) = fixture(); + select(&mut h, id); + key(&mut h, egui::Key::Escape, Modifiers::NONE); + assert_eq!(h.state().selected_object, None); +} + +#[test] +fn the_body_of_a_shape_shows_the_move_cursor() { + let (mut h, id) = fixture(); + let c = rect(&h, id).center(); + h.input_mut().events.push(Event::PointerMoved(c)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Move); +} + +#[test] +fn resizing_a_flat_line_keeps_it_flat() { + let (mut h, id) = fixture_of("line"); + select(&mut h, id); + let before = rect(&h, id); + assert_eq!(before.height(), 0.0, "a new line has no height"); + drag(&mut h, before.right_bottom(), before.right_bottom() + vec2(50.0, 40.0)); + let after = rect(&h, id); + assert!(after.width() > before.width() + 40.0, "{before:?} -> {after:?}"); + assert_eq!(after.height(), 0.0, "{before:?} -> {after:?}"); +} + +#[test] +fn resizing_rotated_flat_lines_and_arrows_keeps_them_flat_and_undoes() { + for kind in ["line", "arrow"] { + let (mut h, id) = fixture_of(kind); + h.state_mut().run("object.move", json!({"kind": "shape", "id": id, "rotation": 90})).unwrap(); + h.run_steps(2); + h.state_mut().selected_object = Some(gridcraft_engine::model::ObjRef::new(gridcraft_engine::model::ObjKind::Shape, id)); + h.run_steps(2); + + let before_anchor = anchor(&h, id); + let before = rect(&h, id); + assert_eq!(before.height(), 0.0, "{kind} starts flat: {before:?}"); + let handle = gridcraft_ui_egui::frame::Handle { x: 1, y: 1 }.at_turned(before, 90.0); + drag(&mut h, handle, handle + vec2(0.0, 50.0)); + + let after = rect(&h, id); + assert!(after.width() > before.width() + 40.0, "{kind}: {before:?} -> {after:?}"); + assert_eq!(after.height(), 0.0, "{kind}: {before:?} -> {after:?}"); + assert_eq!(rotation(&h, id), 90.0); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(anchor(&h, id), before_anchor, "{kind} undo restores its anchor"); + assert_eq!(rotation(&h, id), 90.0, "{kind} undo preserves rotation"); + } +} + +#[test] +fn arrow_keys_follow_the_screen_on_a_right_to_left_sheet() { + let (mut h, id) = fixture(); + h.state_mut().session.execute("view.rightToLeft", json!({"on": true})).unwrap(); + h.run_steps(2); + h.state_mut().selected_object = Some(gridcraft_engine::model::ObjRef::new(gridcraft_engine::model::ObjKind::Shape, id)); + h.run_steps(2); + let x = |h: &Harness| { + let a = anchor(h, id); + h.state().session.doc().unwrap().wb.active().unwrap().col_left(a.cell.col) as f32 + a.dx + }; + let before = x(&h); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let moved = x(&h) - before; + assert!((moved + 6.0).abs() < 0.01, "moved {moved}"); +} + +#[test] +fn an_ink_stroke_shows_no_resize_handles() { + let (mut h, id) = fixture_of("ink"); + select(&mut h, id); + let r = rect(&h, id); + assert!(!handle_at(&h, r.right_bottom()), "ink does not scale with its frame"); +} diff --git a/crates/xlsx/Cargo.toml b/crates/xlsx/Cargo.toml index 6df6000528..8e2f42cb60 100644 --- a/crates/xlsx/Cargo.toml +++ b/crates/xlsx/Cargo.toml @@ -20,6 +20,9 @@ gridcraft-math = { workspace = true } gridcraft-model = { workspace = true } craft-cfb = { workspace = true } craft-csv = { workspace = true } +craft-drawingml = { workspace = true } +craft-math = { workspace = true } +craft-ods = { workspace = true } craft-offcrypto = { workspace = true } craft-opc = { workspace = true } craft-xls = { workspace = true } diff --git a/crates/xlsx/src/chartex.rs b/crates/xlsx/src/chartex.rs index de54c5942a..d90ed3505e 100644 --- a/crates/xlsx/src/chartex.rs +++ b/crates/xlsx/src/chartex.rs @@ -20,7 +20,16 @@ pub const REL_COLORS: &str = "http://schemas.microsoft.com/office/2011/relations /// Kinds written as chartex parts. pub fn is_chartex(k: ChartKind) -> bool { - matches!(k, ChartKind::Histogram | ChartKind::BoxWhisker | ChartKind::Waterfall | ChartKind::Funnel | ChartKind::Treemap | ChartKind::Sunburst) + use craft_drawingml::chart::ChartType; + match k { + ChartKind::Histogram => ChartType::Histogram.is_chartex(), + ChartKind::BoxWhisker => ChartType::BoxWhisker.is_chartex(), + ChartKind::Waterfall => ChartType::Waterfall.is_chartex(), + ChartKind::Funnel => ChartType::Funnel.is_chartex(), + ChartKind::Treemap => ChartType::Treemap.is_chartex(), + ChartKind::Sunburst => ChartType::Sunburst.is_chartex(), + _ => false, + } } /// The `mc:Choice` requirement for a kind's drawing frame: (prefix, namespace). Funnel charts diff --git a/crates/xlsx/src/drawing.rs b/crates/xlsx/src/drawing.rs index 6b4d538bc8..ea9363a837 100644 --- a/crates/xlsx/src/drawing.rs +++ b/crates/xlsx/src/drawing.rs @@ -227,7 +227,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option { // shape (an ellipse, a filled rectangle) it, like any other warp, leaves the shape what its // geometry says. let word_art = prst == "rect" - && (tx_box || (sp.child("noFill").is_some() && !ln.is_some_and(|l| l.child("solidFill").is_some()))) + && (tx_box || (sp.child("noFill").is_some() && ln.is_none_or(|l| l.child("solidFill").is_none()))) && obj.path(&["txBody", "bodyPr", "prstTxWarp"]).is_some_and(|w| w.attr("prst") == Some("textNoShape")); let kind = match prst { _ if word_art => ShapeKind::WordArt, @@ -266,15 +266,22 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option { line: ink, text, format: Default::default(), + rotation: 0.0, math: Default::default(), }); } let fill = sp.child("solidFill").and_then(dml_color).unwrap_or_default(); let line = ln.and_then(|l| l.child("solidFill")).and_then(dml_color).unwrap_or_default(); - let text = obj.child("txBody").map(body_text).unwrap_or_default(); + let text = tb.map(|tb| if has_math { math_body_text(tb) } else { body_text(tb) }).unwrap_or_default(); let mut format = read_text_format(obj.child("txBody")); format.no_line = ln.is_some_and(|l| l.child("noFill").is_some()); - Some(Shape { id: 0, kind, anchor, fill, line, text, format, math: Default::default() }) + let rotation = sp + .child("xfrm") + .and_then(|x| x.attr("rot")) + .and_then(|r| r.parse::().ok()) + .filter(|r| r.is_finite()) + .map_or(0.0, |r| ((r / 60000.0).rem_euclid(360.0)) as f32); + Some(Shape { id: 0, kind, anchor, fill, line, text, format, rotation, math: Default::default() }) } /// A shape's text formatting: vertical anchor (`a:bodyPr anchor`), the first paragraph's @@ -411,6 +418,55 @@ fn body_text(tb: &El) -> String { tb.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::()).collect::>().join("\n") } +/// A rejected Office Math box still needs its visible run text. Do not reinterpret +/// that text as LaTeX. Keep traversal and output bounded independently of conversion. +fn math_body_text(tb: &El) -> String { + const MAX_BYTES: usize = 1 << 20; + fn append(text: &str, out: &mut String) { + let mut end = text.len().min(MAX_BYTES.saturating_sub(out.len())); + while !text.is_char_boundary(end) { + end -= 1; + } + out.push_str(&text[..end]); + } + fn visit(e: &El, depth: usize, left: &mut usize, out: &mut String) { + if depth > 64 || *left == 0 || out.len() >= MAX_BYTES { + return; + } + *left -= 1; + if e.name.ends_with("Pr") { + return; + } + if e.name == "t" { + append(&e.text, out); + } else if e.name == "AlternateContent" { + // Choice and fallback describe the same content, not two text runs. + if let Some(c) = e.child("Fallback").or_else(|| e.child("Choice")) { + visit(c, depth + 1, left, out); + } + } else { + for child in &e.children { + visit(child, depth + 1, left, out); + if *left == 0 || out.len() >= MAX_BYTES { + break; + } + } + } + } + let mut out = String::new(); + let mut left = 100_000; + for (i, p) in tb.kids("p").enumerate() { + if left == 0 || out.len() >= MAX_BYTES { + break; + } + if i > 0 { + append("\n", &mut out); + } + visit(p, 0, &mut left, &mut out); + } + out +} + /// Whether a body without Office Math still holds the text the writer wrote for `src`: the same /// paragraphs, read back through the same parser. The marker joins run text across paragraphs, /// so a paragraph split that changes no character passes it; the text does not. @@ -452,8 +508,15 @@ fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) { } fn xfrm(a: &Anchor, tag: &str) -> String { + xfrm_rot(a, tag, 0.0) +} + +/// `deg` is written as `rot`, in 60000ths of a degree. +fn xfrm_rot(a: &Anchor, tag: &str, deg: f32) -> String { let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64; - format!("<{tag}>", e(a.width), e(a.height)) + let rot = (f64::from(deg.rem_euclid(360.0)) * 60000.0).round() as i64; + let rot = if rot > 0 { format!(" rot=\"{rot}\"") } else { String::new() }; + format!("<{tag}{rot}>", e(a.width), e(a.height)) } pub fn srgb(c: &Color, theme: &Theme) -> Option { @@ -545,7 +608,7 @@ pub fn write_drawing(sheet: &Sheet, theme: &Theme, objs: &[Obj<'_>]) -> String { "{}", id - 1, if tx { " txBox=\"1\"" } else { "" }, - xfrm(&sh.anchor, "a:xfrm") + xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation) ); if let Some(c) = srgb(&sh.fill, theme) { let _ = write!(s, "{c}"); @@ -691,3 +754,23 @@ pub fn image_content_type(ext: &str) -> &'static str { _ => "image/png", } } + +#[cfg(test)] +mod math_fallback_tests { + use super::*; + + #[test] + fn fallback_uses_one_alternative_and_ignores_properties() { + let tb = crate::xml::parse(br#"

hiddenbefore choicefallback after

next

"#).unwrap(); + assert_eq!(math_body_text(&tb), "before fallback after\nnext"); + } + + #[test] + fn fallback_output_cap_keeps_utf8_intact() { + let xml = format!("

a{}

", "λ".repeat(1 << 19)); + let tb = crate::xml::parse(xml.as_bytes()).unwrap(); + let text = math_body_text(&tb); + assert_eq!(text.len(), (1 << 20) - 1); + assert!(text.starts_with('a') && text.ends_with('λ')); + } +} diff --git a/crates/xlsx/src/drawing/ink.rs b/crates/xlsx/src/drawing/ink.rs index 0bfc0911b8..e44e5c15e5 100644 --- a/crates/xlsx/src/drawing/ink.rs +++ b/crates/xlsx/src/drawing/ink.rs @@ -187,6 +187,7 @@ pub(super) fn read(obj: &El, anchor: Anchor) -> Option { line, text, format: Default::default(), + rotation: 0.0, math: Default::default(), }) } diff --git a/crates/xlsx/src/ods.rs b/crates/xlsx/src/ods.rs index 1ef65b6beb..cdf2dff546 100644 --- a/crates/xlsx/src/ods.rs +++ b/crates/xlsx/src/ods.rs @@ -1,32 +1,17 @@ -//! Data-only OpenDocument Spreadsheet import. Formula caches become constants; styles and -//! other ODF features are deliberately not translated. All fixtures are authored in Rust. -//! Format reference: ODF 1.3, part 3, sections 6.1 and 9.1: -//! . +//! Data-only OpenDocument Spreadsheet import backed by `craft-ods`. +//! Formula caches become constants; styles and other ODF features are deliberately not translated. use std::io::{Cursor, Read}; use std::sync::Arc; -use gridcraft_core::date::{days_in_month, serial_from_ymd}; -use gridcraft_core::{CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRef, Value}; +use gridcraft_core::{CellError, CellRef, RangeRef, Value}; use gridcraft_model::{Cell, NumFmt, Sheet, StyleId, Workbook}; -use quick_xml::NsReader; -use quick_xml::XmlVersion; -use quick_xml::events::{BytesStart, Event}; -use quick_xml::name::ResolveResult; -use crate::package::{MAX_ENTRIES, Package}; +use crate::package::MAX_ENTRIES; +use crate::read::SheetNames; use crate::{IoError, ReadReport}; const MIME: &[u8] = b"application/vnd.oasis.opendocument.spreadsheet"; -const OFFICE: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:office:1.0"; -const TABLE: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:table:1.0"; -const TEXT: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:text:1.0"; -const CALC_EXT: &[u8] = b"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0"; -const MANIFEST: &[u8] = b"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"; -const MAX_CELLS: u64 = 1_000_000; -const MAX_MERGES: u64 = 100_000; -const MAX_CELL_TEXT: usize = 1024 * 1024; -const MAX_TEXT: u64 = 64 * 1024 * 1024; const MAX_SHEETS: usize = 1024; /// Reads only the small, exact mimetype entry, including when the ZIP uses compression. @@ -48,637 +33,120 @@ pub(crate) fn has_mimetype(bytes: &[u8]) -> bool { /// imported as constants, so editing their inputs does not recalculate the original formula. /// Always inspect the returned warnings. Saving to ODS is not supported. pub fn read_ods(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> { - let mut package = Package::open(bytes)?; + // The exact mimetype, as `sniff` requires: craft-ods alone accepts some near misses. if !has_mimetype(bytes) { return Err(IoError::Format("missing or invalid ODS mimetype".into())); } - if let Some(manifest) = package.read("META-INF/manifest.xml")? { - check_manifest(&manifest)?; - } - let content = package.read("content.xml")?.ok_or_else(|| IoError::Format("ODS content.xml is missing".into()))?; - let mut import = Import::new(); - import.parse(&content)?; - if import.wb.sheets.is_empty() { + let book = craft_ods::read(bytes, &craft_ods::Options::default()).map_err(map_error)?; + if book.sheets.is_empty() { return Err(IoError::Format("ODS contains no worksheets".into())); } - Ok((import.wb, import.report)) -} + if book.sheets.len() > MAX_SHEETS { + return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into())); + } -fn is_ns(ns: ResolveResult<'_>, expected: &[u8]) -> bool { - matches!(ns, ResolveResult::Bound(n) if n.as_ref() == expected) -} + // `Workbook::new` starts with an empty Sheet1; the ODS tables are the only sheets. + let mut wb = Workbook::new(); + wb.sheets.clear(); + let mut names = SheetNames::default(); + let mut report = ReadReport::default(); + report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported."); -fn attr(reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>, ns: &[u8], name: &[u8]) -> Result, IoError> { - let mut found = None; - for a in e.attributes() { - let a = a.map_err(|e| IoError::Xml(e.to_string()))?; - let (resolved, local) = reader.resolver_mut().resolve_attribute(a.key); - if is_ns(resolved, ns) && local.as_ref() == name { - let value = a.normalized_value(XmlVersion::Explicit1_0).map_err(|e| IoError::Xml(e.to_string()))?; - if value.len() > MAX_CELL_TEXT { - return Err(IoError::TooLarge("ODS attribute exceeds 1 MiB".into())); - } - found = Some(value.into_owned()); + let mut warned_rename = false; + let mut warned_unavailable = false; + + for src_sheet in book.sheets { + let mut name = names.unique(src_sheet.name.trim_matches('\''), wb.sheets.len()); + if wb.check_sheet_name(&name, None).is_err() { + name = wb.next_sheet_name(); + names.insert(&name); } - } - Ok(found) -} - -fn positive(value: Option, default: u32, limit: u32) -> Result { - let n = match value { - Some(s) => s.parse::().map_err(|_| IoError::Format("invalid ODS repeat or span count".into()))?, - None => default, - }; - if n == 0 || n > limit { - return Err(IoError::TooLarge("ODS repeat or span exceeds worksheet bounds".into())); - } - Ok(n) -} - -fn xml_error(e: impl std::fmt::Display) -> IoError { - IoError::Xml(format!("ODS: {e}")) -} - -fn check_manifest(bytes: &[u8]) -> Result<(), IoError> { - let mut reader = NsReader::from_reader(bytes); - let mut depth = 0usize; - let mut root_seen = false; - loop { - let event = reader.read_event().map_err(xml_error)?; - match &event { - Event::Start(e) | Event::Empty(e) => { - let (ns, name) = reader.resolver_mut().resolve_element(e.name()); - if is_ns(ns.clone(), MANIFEST) && name.as_ref() == b"encryption-data" { - return Err(IoError::Format("encrypted ODS files are not supported".into())); - } - if depth == 0 { - if root_seen || !is_ns(ns, MANIFEST) || name.as_ref() != b"manifest" { - return Err(xml_error("expected one manifest:manifest root")); - } - root_seen = true; - } - if matches!(event, Event::Start(_)) { - depth += 1; - if depth > crate::xml::MAX_DEPTH { - return Err(xml_error("manifest nested too deeply")); - } - } - } - Event::End(_) => depth = depth.checked_sub(1).ok_or_else(|| xml_error("unexpected manifest closing element"))?, - Event::DocType(_) => return Err(xml_error("DOCTYPE is not supported")), - Event::Eof => break, - _ => {} + let mut sheet = Sheet::new(name); + if !warned_rename && sheet.name != src_sheet.name { + warned_rename = true; + report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names."); } - } - if !root_seen || depth != 0 { - return Err(xml_error("incomplete manifest")); - } - Ok(()) -} -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Tag { - Document, - Body, - Spreadsheet, - Table, - Rows, - Row, - Cell, - Covered, - Paragraph, - Inline, - Space, - Tab, - Break, - Other, -} - -fn tag(reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>) -> Tag { - let (ns, name) = reader.resolver_mut().resolve_element(e.name()); - let local = name.as_ref(); - if is_ns(ns.clone(), OFFICE) { - return match local { - b"document-content" => Tag::Document, - b"body" => Tag::Body, - b"spreadsheet" => Tag::Spreadsheet, - _ => Tag::Other, - }; - } - if is_ns(ns.clone(), TABLE) { - return match local { - b"table" => Tag::Table, - b"table-row-group" | b"table-header-rows" | b"table-rows" => Tag::Rows, - b"table-row" => Tag::Row, - b"table-cell" => Tag::Cell, - b"covered-table-cell" => Tag::Covered, - _ => Tag::Other, - }; - } - if is_ns(ns, TEXT) { - return match local { - b"p" | b"h" => Tag::Paragraph, - b"span" | b"a" | b"meta" | b"meta-field" | b"ruby" | b"ruby-base" => Tag::Inline, - b"s" => Tag::Space, - b"tab" => Tag::Tab, - b"line-break" => Tag::Break, - _ => Tag::Other, - }; - } - Tag::Other -} - -struct SheetDraft { - sheet: Sheet, - depth: usize, - row: u32, -} -struct RowDraft { - depth: usize, - repeat: u32, - col: u32, - cells: Vec, -} -struct RepeatedCell { - col: u32, - repeat: u32, - width: u32, - height: u32, - cell: Cell, -} -struct CellDraft { - depth: usize, - repeat: u32, - width: u32, - height: u32, - covered: bool, - kind: Option, - raw: Option, - formula: bool, - text: String, - paragraph: Option, - paragraphs: usize, - paragraph_started: bool, - pending_space: bool, -} -struct Import { - wb: Workbook, - report: ReadReport, - stack: Vec, - sheet: Option, - row: Option, - cell: Option, - cells: u64, - merges: u64, - text: u64, - formats: Vec<(&'static str, StyleId)>, - spreadsheet_seen: bool, - names: crate::read::SheetNames, -} - -impl Import { - fn new() -> Self { - let mut wb = Workbook::new(); - wb.sheets.clear(); - let mut report = ReadReport::default(); - report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported."); - Self { - wb, - report, - stack: vec![], - sheet: None, - row: None, - cell: None, - cells: 0, - merges: 0, - text: 0, - formats: vec![], - spreadsheet_seen: false, - names: Default::default(), - } - } - - fn parse(&mut self, bytes: &[u8]) -> Result<(), IoError> { - let mut reader = NsReader::from_reader(bytes); - let mut root_seen = false; - loop { - match reader.read_event().map_err(xml_error)? { - Event::Start(e) => { - if self.stack.len() >= crate::xml::MAX_DEPTH { - return Err(xml_error("XML nested too deeply")); - } - if self.stack.is_empty() { - if root_seen || tag(&mut reader, &e) != Tag::Document { - return Err(xml_error("expected one office:document-content root")); - } - root_seen = true; - } - self.start(&mut reader, &e)?; + for (coord, src_cell) in src_sheet.cells { + // A typed value that cannot be read (an unparsable number or date, an error cache, + // a formula without a result) keeps what the cell showed, else its raw value. + let Some(value) = src_cell.value().map(map_value) else { + if !warned_unavailable { + warned_unavailable = true; + report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result]."); } - Event::Empty(e) => { - if self.stack.is_empty() { - return Err(xml_error("expected office:document-content with a spreadsheet")); - } - self.start(&mut reader, &e)?; - self.end()?; - } - Event::End(_) => self.end()?, - Event::Text(t) => { - let text = t.xml_content(XmlVersion::Explicit1_0).map_err(xml_error)?; - if self.stack.is_empty() && !text.trim().is_empty() { - return Err(xml_error("text outside the document")); - } - self.append(&text)?; - } - Event::CData(t) => self.append(&t.decode().map_err(xml_error)?)?, - Event::GeneralRef(r) => { - let ch = match r.resolve_char_ref().map_err(xml_error)? { - Some(c) => c, - None => match &*r { - b"amp" => '&', - b"lt" => '<', - b"gt" => '>', - b"apos" => '\'', - b"quot" => '"', - _ => return Err(xml_error("unsupported XML entity")), - }, - }; - self.append(ch.encode_utf8(&mut [0; 4]))?; - } - Event::DocType(_) => return Err(xml_error("DOCTYPE is not supported")), - Event::Eof => break, - _ => {} - } - } - if !root_seen || !self.stack.is_empty() || !self.spreadsheet_seen { - return Err(xml_error("incomplete ODS document")); - } - Ok(()) - } - - fn start(&mut self, reader: &mut NsReader<&[u8]>, e: &BytesStart<'_>) -> Result<(), IoError> { - let t = tag(reader, e); - let depth = self.stack.len(); - match t { - Tag::Spreadsheet if self.stack == [Tag::Document, Tag::Body] => { - if self.spreadsheet_seen { - return Err(xml_error("multiple spreadsheets in one document")); - } - self.spreadsheet_seen = true; - } - Tag::Table if self.stack == [Tag::Document, Tag::Body, Tag::Spreadsheet] => { - if self.wb.sheets.len() >= MAX_SHEETS { - return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into())); - } - let original = attr(reader, e, TABLE, b"name")?.unwrap_or_default(); - let mut name = self.names.unique(original.trim_matches('\''), self.wb.sheets.len()); - if self.wb.check_sheet_name(&name, None).is_err() { - name = self.wb.next_sheet_name(); - self.names.insert(&name); - } - if name != original { - self.report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names."); - } - self.sheet = Some(SheetDraft { sheet: Sheet::new(name), depth, row: 0 }); - } - Tag::Row if self.sheet.as_ref().is_some_and(|s| self.stack.get(s.depth + 1..).is_some_and(|p| p.iter().all(|t| *t == Tag::Rows))) => { - self.row = - Some(RowDraft { depth, repeat: positive(attr(reader, e, TABLE, b"number-rows-repeated")?, 1, u32::MAX)?, col: 0, cells: vec![] }); - } - Tag::Cell | Tag::Covered if self.row.as_ref().is_some_and(|r| depth == r.depth + 1) => { - let kind = if attr(reader, e, CALC_EXT, b"value-type")?.as_deref() == Some("error") { - Some("error".into()) + let text = if !src_cell.text.is_empty() { + src_cell.text.as_str() + } else if let Some(raw) = src_cell.raw.as_deref() { + raw + } else if src_cell.formula.is_some() { + "[Unavailable ODS formula result]" } else { - attr(reader, e, OFFICE, b"value-type")? + "[Unsupported ODS value]" }; - let key: &[u8] = match kind.as_deref() { - Some("boolean") => b"boolean-value", - Some("date") => b"date-value", - Some("time") => b"time-value", - Some("string") => b"string-value", - _ => b"value", - }; - self.cell = Some(CellDraft { - depth, - repeat: positive(attr(reader, e, TABLE, b"number-columns-repeated")?, 1, u32::MAX)?, - width: positive(attr(reader, e, TABLE, b"number-columns-spanned")?, 1, MAX_COLS)?, - height: positive(attr(reader, e, TABLE, b"number-rows-spanned")?, 1, MAX_ROWS)?, - covered: t == Tag::Covered, - kind, - raw: attr(reader, e, OFFICE, key)?, - formula: attr(reader, e, TABLE, b"formula")?.is_some(), - text: String::new(), - paragraph: None, - paragraphs: 0, - paragraph_started: false, - pending_space: false, - }); - } - Tag::Paragraph if self.cell.as_ref().is_some_and(|c| depth == c.depth + 1) => { - if let Some(cell) = self.cell.as_mut() { - if cell.paragraphs > 0 { - push_text(&mut cell.text, "\n")?; - } - cell.paragraph = Some(depth); - cell.paragraphs += 1; - cell.paragraph_started = false; - cell.pending_space = false; - } - } - Tag::Space | Tag::Tab | Tag::Break if self.captures_text() => { - let count = if t == Tag::Space { - let n = attr(reader, e, TEXT, b"c")?.map(|s| s.parse::()).transpose().map_err(xml_error)?.unwrap_or(1); - if n as usize > MAX_CELL_TEXT { - return Err(IoError::TooLarge("ODS repeated spaces exceed 1 MiB".into())); - } - n - } else { - 1 - }; - let value = match t { - Tag::Space => " ", - Tag::Tab => "\t", - _ => "\n", - }; - if let Some(cell) = self.cell.as_mut() { - if cell.pending_space { - push_text(&mut cell.text, " ")?; - cell.pending_space = false; - } - cell.paragraph_started = true; - if cell.text.len().saturating_add(count as usize) > MAX_CELL_TEXT { - return Err(IoError::TooLarge("ODS cell text exceeds 1 MiB".into())); - } - for _ in 0..count { - cell.text.push_str(value); - } - } - } - _ => {} - } - self.stack.push(t); - Ok(()) - } + sheet.set_cell(CellRef::new(coord.row, coord.col), Cell::styled(Value::Text(Arc::from(text)), StyleId::DEFAULT)); + continue; + }; - fn captures_text(&self) -> bool { - self.cell - .as_ref() - .and_then(|c| c.paragraph) - .is_some_and(|depth| self.stack.get(depth..).is_some_and(|p| p.iter().all(|t| matches!(t, Tag::Paragraph | Tag::Inline)))) - } - - fn append(&mut self, text: &str) -> Result<(), IoError> { - if self.captures_text() - && let Some(cell) = self.cell.as_mut() - { - // ODF 1.3 section 6.1.2: collapse XML whitespace across inline runs, - // but expand explicit text:s/tab/line-break elements separately. - for ch in text.chars() { - if matches!(ch, ' ' | '\t' | '\n' | '\r') { - cell.pending_space = cell.paragraph_started; - } else { - if cell.pending_space { - push_text(&mut cell.text, " ")?; - cell.pending_space = false; - } - push_text(&mut cell.text, ch.encode_utf8(&mut [0; 4]))?; - cell.paragraph_started = true; + let format = match src_cell.value_type { + Some(craft_ods::ValueType::Date) => { + let with_time = src_cell.raw.as_deref().and_then(craft_ods::date_serial).is_some_and(|(_, time)| time); + Some(if with_time { "yyyy-mm-dd hh:mm:ss.000" } else { "yyyy-mm-dd" }) } - } - } - Ok(()) - } - - fn end(&mut self) -> Result<(), IoError> { - self.stack.pop().ok_or_else(|| xml_error("unexpected closing element"))?; - let depth = self.stack.len(); - if let Some(cell) = self.cell.as_mut() - && cell.paragraph == Some(depth) - { - cell.paragraph = None; - } - if self.cell.as_ref().is_some_and(|c| c.depth == depth) { - self.finish_cell()?; - } - if self.row.as_ref().is_some_and(|r| r.depth == depth) { - self.finish_row()?; - } - if self.sheet.as_ref().is_some_and(|s| s.depth == depth) - && let Some(sheet) = self.sheet.take() - { - self.wb.sheets.push(Arc::new(sheet.sheet)); - } - Ok(()) - } - - fn finish_cell(&mut self) -> Result<(), IoError> { - let Some(draft) = self.cell.take() else { return Ok(()) }; - let cell = self.convert(&draft); - let (width, height) = if draft.covered { (1, 1) } else { (draft.width, draft.height) }; - let Some(row) = self.row.as_mut() else { return Ok(()) }; - let kept = !cell.is_blank() || width > 1 || height > 1; - // Writers pad rows with blank repeats up to their own (possibly wider) sheet edge; - // blank cells past ours carry no data, so clip them instead of rejecting the file. - let end = match row.col.checked_add(draft.repeat).filter(|n| *n <= MAX_COLS) { - Some(end) => end, - None if !kept => MAX_COLS, - None => return Err(IoError::TooLarge("ODS row exceeds worksheet width".into())), - }; - if kept { - // Charge the text a row keeps before the row is done, so a row of many long cells is - // refused as it grows; finish_row charges the row's repeats beyond the first. - if let Value::Text(t) = &cell.value { - self.text = self.text.saturating_add(u64::from(draft.repeat).saturating_mul(t.len() as u64)); - if self.text > MAX_TEXT { - return Err(IoError::TooLarge("ODS expands beyond the import limit (64 MiB of text)".into())); - } - } - row.cells.push(RepeatedCell { col: row.col, repeat: draft.repeat, width, height, cell }); - } - row.col = end; - Ok(()) - } - - fn convert(&mut self, draft: &CellDraft) -> Cell { - let raw = draft.raw.as_deref(); - let mut format = None; - let value = match draft.kind.as_deref() { - Some("float" | "percentage" | "currency") => raw.and_then(|s| s.parse::().ok()).filter(|n| n.is_finite()).map(|n| { - if draft.kind.as_deref() == Some("percentage") { - format = Some("0.00%"); - } - Value::Number(n) - }), - Some("boolean") => match raw { - Some("true" | "1") => Some(Value::Bool(true)), - Some("false" | "0") => Some(Value::Bool(false)), + Some(craft_ods::ValueType::Time) => Some("[h]:mm:ss.000"), + Some(craft_ods::ValueType::Percentage) => Some("0.00%"), + Some(craft_ods::ValueType::Currency) => Some("#,##0.00"), _ => None, - }, - Some("string") if raw.is_some() || draft.paragraphs > 0 || !draft.formula => Some(Value::Text(Arc::from(raw.unwrap_or(&draft.text)))), - Some("void") if !draft.formula => Some(Value::Empty), - Some("date") => raw.and_then(parse_date).map(|(n, f)| { - format = Some(f); - Value::Number(n) - }), - Some("time") => raw.and_then(parse_duration).map(|n| { - format = Some("[h]:mm:ss.000"); - Value::Number(n) - }), - None if !draft.formula => Some(if draft.text.is_empty() { Value::Empty } else { Value::Text(Arc::from(draft.text.as_str())) }), - _ => None, - }; - let value = value.unwrap_or_else(|| { - self.report.warn("Some ODS values or formula caches were unsupported or missing; their displayed text (or raw value) was kept as text. A formula without either is marked [Unavailable ODS formula result]."); - let text = if !draft.text.is_empty() { draft.text.as_str() } else if let Some(raw) = raw { raw } else if draft.formula { "[Unavailable ODS formula result]" } else { "[Unsupported ODS value]" }; - Value::Text(Arc::from(text)) - }); - let style = match format { - Some(code) => match self.formats.iter().find(|(f, _)| *f == code) { - Some((_, id)) => *id, - None => { - let id = self.wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)); - self.formats.push((code, id)); - id - } - }, - None => StyleId::DEFAULT, - }; - Cell { style, ..Cell::value(value) } + }; + let style_id = format.map_or(StyleId::DEFAULT, |code| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code))); + + let target_coord = CellRef::new(coord.row, coord.col); + sheet.set_cell(target_coord, Cell::styled(value, style_id)); + } + + for m in src_sheet.merges { + let range = RangeRef::new(CellRef::new(m.first.row, m.first.col), CellRef::new(m.last.row, m.last.col)); + sheet.merges.push(range); + } + wb.sheets.push(Arc::new(sheet)); } - fn finish_row(&mut self) -> Result<(), IoError> { - let Some(row) = self.row.take() else { return Ok(()) }; - let Some(sheet) = self.sheet.as_mut() else { return Ok(()) }; - // Blank trailing row repeats past the sheet edge (e.g. from larger-sheet writers) are clipped. - let end = match sheet.row.checked_add(row.repeat).filter(|n| *n <= MAX_ROWS) { - Some(end) => end, - None if row.cells.is_empty() => MAX_ROWS, - None => return Err(IoError::TooLarge("ODS exceeds worksheet height".into())), - }; - for entry in row.cells { - let count = u64::from(entry.repeat) * u64::from(row.repeat); - if !entry.cell.is_blank() { - self.cells = self.cells.saturating_add(count); - if let Value::Text(t) = &entry.cell.value { - let repeats = count.saturating_sub(u64::from(entry.repeat)); - self.text = self.text.saturating_add(repeats.saturating_mul(t.len() as u64)); - } - } - let merged = entry.width > 1 || entry.height > 1; - if merged { - self.merges = self.merges.saturating_add(count); - } - if self.cells > MAX_CELLS || self.merges > MAX_MERGES || self.text > MAX_TEXT { - return Err(IoError::TooLarge("ODS expands beyond the import limit (1 million cells, 100000 merges or 64 MiB of text)".into())); - } - let last_col = entry.col.checked_add(entry.repeat - 1).and_then(|c| c.checked_add(entry.width - 1)); - let last_row = end.checked_add(entry.height - 1); - if last_col.is_none_or(|c| c >= MAX_COLS) || last_row.is_none_or(|r| r > MAX_ROWS) { - return Err(IoError::TooLarge("ODS merged cell exceeds worksheet bounds".into())); - } - if merged && ((entry.repeat > 1 && entry.width > 1) || (row.repeat > 1 && entry.height > 1)) { - return Err(IoError::Format("repeated ODS cells have overlapping merges".into())); - } - for r in sheet.row..end { - for c in entry.col..entry.col + entry.repeat { - let pos = CellRef::new(r, c); - if !entry.cell.is_blank() { - sheet.sheet.cells.set(pos, entry.cell.clone()); - } - if merged { - sheet.sheet.merges.push(RangeRef::new(pos, CellRef::new(r + entry.height - 1, c + entry.width - 1))); - } - } - } - } - sheet.row = end; - Ok(()) + Ok((wb, report)) +} + +fn map_error(e: craft_ods::Error) -> IoError { + match e { + craft_ods::Error::Encrypted => IoError::Format("encrypted ODS files are not supported".into()), + craft_ods::Error::Xml(msg) => IoError::Xml(format!("ODS: {msg}")), + craft_ods::Error::TooLarge(msg) => IoError::TooLarge(msg), + craft_ods::Error::Invalid(msg) => IoError::Format(msg), + other => IoError::Format(other.to_string()), } } -fn push_text(out: &mut String, text: &str) -> Result<(), IoError> { - if out.len().saturating_add(text.len()) > MAX_CELL_TEXT { - return Err(IoError::TooLarge("ODS cell text exceeds 1 MiB".into())); +fn map_value(v: craft_ods::Value) -> Value { + match v { + craft_ods::Value::Empty => Value::Empty, + craft_ods::Value::Number(n) => Value::Number(n), + craft_ods::Value::Text(s) => Value::Text(s), + craft_ods::Value::Bool(b) => Value::Bool(b), + craft_ods::Value::Error(e) => Value::Error(map_cell_error(e)), } - out.push_str(text); - Ok(()) } -/// Support unzoned ISO calendar dates and times. A timezone, invalid date or out-of-range -/// calendar year remains text; never silently discard an offset or roll an invalid date. -fn parse_date(s: &str) -> Option<(f64, &'static str)> { - let (date, time) = s.split_once('T').map_or((s, None), |(d, t)| (d, Some(t))); - if date.len() != 10 || date.get(4..5)? != "-" || date.get(7..8)? != "-" { - return None; +fn map_cell_error(e: craft_ods::CellError) -> CellError { + match e { + craft_ods::CellError::Null => CellError::Null, + craft_ods::CellError::Div0 => CellError::Div0, + craft_ods::CellError::Value => CellError::Value, + craft_ods::CellError::Ref => CellError::Ref, + craft_ods::CellError::Name => CellError::Name, + craft_ods::CellError::Num => CellError::Num, + craft_ods::CellError::NA => CellError::NA, + craft_ods::CellError::GettingData => CellError::GettingData, + craft_ods::CellError::Spill => CellError::Spill, + craft_ods::CellError::Calc => CellError::Calc, + craft_ods::CellError::Blocked => CellError::Blocked, + _ => CellError::Value, } - let year: i32 = digits(date.get(..4)?)?.parse().ok()?; - let month: u32 = digits(date.get(5..7)?)?.parse().ok()?; - let day: u32 = digits(date.get(8..10)?)?.parse().ok()?; - if !(1900..=9999).contains(&year) || !(1..=12).contains(&month) || day == 0 || day > days_in_month(year, month) { - return None; - } - let day = serial_from_ymd(DateSystem::D1900, year.into(), month.into(), day.into())?; - let Some(time) = time else { return Some((day, "yyyy-mm-dd")) }; - let mut parts = time.split(':'); - let h = parts.next()?; - let m = parts.next()?; - let sec = parts.next()?; - if parts.next().is_some() || h.len() != 2 || m.len() != 2 || sec.split('.').next()?.len() != 2 { - return None; - } - let h: u32 = digits(h)?.parse().ok()?; - let m: u32 = digits(m)?.parse().ok()?; - let sec = decimal(sec)?; - if h >= 24 || m >= 60 || sec >= 60.0 { - return None; - } - Some((day + (h as f64 * 3600.0 + m as f64 * 60.0 + sec) / 86400.0, "yyyy-mm-dd hh:mm:ss.000")) -} - -fn digits(s: &str) -> Option<&str> { - (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then_some(s) -} -fn decimal(s: &str) -> Option { - match s.split_once('.') { - Some((a, b)) => { - digits(a)?; - digits(b)?; - } - None => { - digits(s)?; - } - } - s.parse::().ok().filter(|n| n.is_finite()) -} - -/// A bounded ISO day/time duration. Calendar years/months cannot be represented as days. -fn parse_duration(s: &str) -> Option { - let (negative, s) = s.strip_prefix('-').map_or((false, s), |s| (true, s)); - let mut rest = s.strip_prefix('P')?; - let mut total = 0.0; - let mut any = false; - if let Some((days, tail)) = rest.split_once('D') { - total += digits(days)?.parse::().ok()? * 86400.0; - rest = tail; - any = true; - } - if let Some(mut time) = rest.strip_prefix('T') { - let mut time_any = false; - for (unit, factor) in [('H', 3600.0), ('M', 60.0), ('S', 1.0)] { - if let Some((n, tail)) = time.split_once(unit) { - let value = if unit == 'S' { decimal(n)? } else { digits(n)?.parse::().ok()? }; - total += value * factor; - time = tail; - time_any = true; - } - } - if !time.is_empty() || !time_any { - return None; - } - any = true; - } else if !rest.is_empty() { - return None; - } - let days = total / 86400.0; - (any && days.is_finite() && days <= 2_958_465.0).then_some(if negative { -days } else { days }) } diff --git a/crates/xlsx/src/omml.rs b/crates/xlsx/src/omml.rs index 1490b9ea58..0e1c4d0717 100644 --- a/crates/xlsx/src/omml.rs +++ b/crates/xlsx/src/omml.rs @@ -4,38 +4,131 @@ use crate::xml::El; -/// Deepest OMML nesting converted. +/// Deepest OMML nesting marked. const MAX_DEPTH: usize = 64; -/// Longest LaTeX the conversion produces before it gives up. `gridcraft_math::check` refuses a -/// longer source anyway, so converting the rest of a wide or long equation would only spend time -/// and memory on a hostile file. -const MAX_OUT_BYTES: usize = gridcraft_math::MAX_SOURCE_BYTES; /// The LaTeX for an `m:oMath` (or `m:oMathPara`) element, if every part is in the subset and the /// result lays out. pub fn to_latex(e: &El) -> Option { - let out = convert(e)?; + if e.name != "oMathPara" && e.name != "oMath" { + return None; + } + validate_conversion(e, 0, false, &mut (1 << 20))?; + let mut xml = String::new(); + write_el(e, &mut xml); + let math = craft_math::omml::read_str(&xml)?; + let out = craft_math::math_latex::to_latex(&math.nodes); + let out = out.trim().to_string(); (!out.is_empty() && gridcraft_math::check(&out).is_ok()).then_some(out) } -/// The conversion itself, before the final check: `None` for a construct outside the subset, an -/// equation nested past [`MAX_DEPTH`] or one whose LaTeX exceeds [`MAX_OUT_BYTES`]. -fn convert(e: &El) -> Option { - let mut out = String::new(); - match e.name.as_str() { - "oMathPara" => { - let maths: Vec<&El> = e.kids("oMath").collect(); - for (i, m) in maths.iter().enumerate() { - if i > 0 { - out.push_str(" \\\\ "); - } - seq(m, &mut out, 0)?; - } +// The shared reader is tolerant; this importer must fall back instead of losing +// equation content. Bound escaped XML before serializing or descending further. +fn validate_conversion(e: &El, depth: usize, property: bool, remaining: &mut usize) -> Option<()> { + if depth > MAX_DEPTH { + return None; + } + let charge = e.name.len().checked_mul(2)?.checked_add(16)?.checked_add(e.text.len().checked_mul(6)?)?; + *remaining = remaining.checked_sub(charge)?; + for (key, value) in &e.attrs { + *remaining = remaining.checked_sub(key.len().checked_add(value.len().checked_mul(6)?)?.checked_add(8)?)?; + } + let property = property || e.name.ends_with("Pr"); + if !property + && !matches!( + e.name.as_str(), + "oMath" + | "oMathPara" + | "r" + | "t" + | "f" + | "num" + | "den" + | "rad" + | "deg" + | "e" + | "sSup" + | "sSub" + | "sSubSup" + | "sPre" + | "sub" + | "sup" + | "nary" + | "d" + | "m" + | "mr" + | "eqArr" + | "acc" + | "bar" + | "groupChr" + | "limLow" + | "limUpp" + | "lim" + | "func" + | "fName" + | "borderBox" + | "phant" + | "box" + ) + { + return None; + } + // These limits truncate in the shared reader rather than refusing the matrix. + if (e.name == "m" && e.kids("mr").count() > 1000) || (e.name == "mr" && e.kids("e").count() > 64) { + return None; + } + // The pinned emitter treats a literal caret as syntax. Preserve original text + // rather than inventing a superscript; structural scripts remain supported. + if e.name == "t" && e.text.contains('^') { + return None; + } + for child in &e.children { + validate_conversion(child, depth + 1, property, remaining)?; + } + Some(()) +} + +fn write_el(e: &El, out: &mut String) { + out.push_str(" seq(e, &mut out, 0)?, - _ => return None, + out.push_str("=\""); + push_xml_escaped(v, out); + out.push('"'); + } + if e.children.is_empty() && e.text.is_empty() { + out.push_str("/>"); + return; + } + out.push('>'); + if !e.text.is_empty() { + push_xml_escaped(&e.text, out); + } + for c in &e.children { + write_el(c, out); + } + out.push_str("'); +} + +fn push_xml_escaped(s: &str, out: &mut String) { + for ch in s.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(ch), + } } - Some(out.trim().to_string()) } /// The first `m:oMath`/`m:oMathPara` under `e` (an `a14:m` element or a paragraph), searched to a @@ -178,35 +271,8 @@ fn mark_bytes(h: &mut u64, bytes: &[u8]) { } /// Children in order, skipping property elements. -fn seq(e: &El, out: &mut String, depth: usize) -> Option<()> { - if depth > MAX_DEPTH { - return None; - } - for c in &e.children { - node(c, out, depth + 1)?; - if out.len() > MAX_OUT_BYTES { - return None; - } - } - Some(()) -} - -/// `{…}` around a child's contents (empty group when the child is missing). -fn group(e: Option<&El>, out: &mut String, depth: usize) -> Option<()> { - out.push('{'); - if let Some(e) = e { - seq(e, out, depth)?; - } - out.push('}'); - Some(()) -} - -/// The property elements and the properties in them that this converter reads, so the ones -/// that decide what an equation says beyond its structure and text. [`body_marker`] hashes -/// exactly these, and [`val`] and [`on`] read only these, so the two cannot drift: a property -/// read here without a row in this table reads as absent, which the conversion tests show. const PROPERTIES: &[(&str, &[&str])] = &[ - ("rPr", &["nor", "sty", "scr"]), + ("rPr", &["nor", "sty", "scr", "lit"]), ("fPr", &["type"]), ("radPr", &["degHide"]), ("naryPr", &["chr", "limLoc", "subHide", "supHide"]), @@ -221,446 +287,6 @@ fn read_properties(pr: &str) -> &'static [&'static str] { PROPERTIES.iter().find(|(name, _)| *name == pr).map_or(&[], |(_, names)| names) } -/// The `val` of property `name` in the property element `props`, when the converter reads it. -fn val<'a>(props: Option<&'a El>, name: &str) -> Option<&'a str> { - props.filter(|p| read_properties(&p.name).contains(&name)).and_then(|p| p.child(name)).and_then(|c| c.attr("val")) -} - -/// Whether the switch `name` in the property element `props` is on, when the converter reads it. -fn on(props: Option<&El>, name: &str) -> bool { - props - .filter(|p| read_properties(&p.name).contains(&name)) - .and_then(|p| p.child(name)) - .is_some_and(|c| c.attr("val").is_none_or(|v| v == "1" || v == "on" || v == "true")) -} - -/// LaTeX for one character of a math run. -fn char_latex(c: char) -> Option<&'static str> { - Some(match c { - 'α' => "\\alpha ", - 'β' => "\\beta ", - 'γ' => "\\gamma ", - 'δ' => "\\delta ", - 'ε' => "\\varepsilon ", - 'ϵ' => "\\epsilon ", - 'ζ' => "\\zeta ", - 'η' => "\\eta ", - 'θ' => "\\theta ", - 'ϑ' => "\\vartheta ", - 'ι' => "\\iota ", - 'κ' => "\\kappa ", - 'λ' => "\\lambda ", - 'μ' => "\\mu ", - 'ν' => "\\nu ", - 'ξ' => "\\xi ", - 'π' => "\\pi ", - 'ρ' => "\\rho ", - 'σ' => "\\sigma ", - 'τ' => "\\tau ", - 'υ' => "\\upsilon ", - 'φ' => "\\varphi ", - 'ϕ' => "\\phi ", - 'χ' => "\\chi ", - 'ψ' => "\\psi ", - 'ω' => "\\omega ", - 'Γ' => "\\Gamma ", - 'Δ' => "\\Delta ", - 'Θ' => "\\Theta ", - 'Λ' => "\\Lambda ", - 'Ξ' => "\\Xi ", - 'Π' => "\\Pi ", - 'Σ' => "\\Sigma ", - 'Υ' => "\\Upsilon ", - 'Φ' => "\\Phi ", - 'Ψ' => "\\Psi ", - 'Ω' => "\\Omega ", - '±' => "\\pm ", - '∓' => "\\mp ", - '×' => "\\times ", - '÷' => "\\div ", - '⋅' | '·' => "\\cdot ", - '−' => "-", - '≤' => "\\le ", - '≥' => "\\ge ", - '≠' => "\\ne ", - '≈' => "\\approx ", - '≡' => "\\equiv ", - '∼' => "\\sim ", - '∝' => "\\propto ", - '∞' => "\\infty ", - '∂' => "\\partial ", - '∇' => "\\nabla ", - '∀' => "\\forall ", - '∃' => "\\exists ", - '∈' => "\\in ", - '∉' => "\\notin ", - '⊂' => "\\subset ", - '⊆' => "\\subseteq ", - '⊃' => "\\supset ", - '∪' => "\\cup ", - '∩' => "\\cap ", - '∅' => "\\emptyset ", - '→' => "\\to ", - '←' => "\\leftarrow ", - '⇒' => "\\Rightarrow ", - '⇔' => "\\Leftrightarrow ", - '…' => "\\ldots ", - '⋯' => "\\cdots ", - '∘' => "\\circ ", - '{' => "\\{", - '}' => "\\}", - '%' => "\\%", - '#' => "\\#", - '&' => "\\&", - '$' => "\\$", - '_' => "\\_", - '\\' => "\\backslash ", - '~' => "\\sim ", - '^' => "\\hat{}", - _ => return None, - }) -} - -fn run_text(r: &El) -> String { - r.kids("t").map(|t| t.text.as_str()).collect() -} - -/// Appends `s` escaped for `\text{…}`; `None` once the LaTeX exceeds [`MAX_OUT_BYTES`], checked -/// after every character so that a long run never expands in full. -fn escape_text(s: &str, out: &mut String) -> Option<()> { - for c in s.chars() { - match c { - '{' | '}' | '%' | '#' | '&' | '$' | '_' => { - out.push('\\'); - out.push(c); - } - '\\' => out.push_str("\\textbackslash "), - '^' | '~' => out.push(' '), - c => out.push(c), - } - if out.len() > MAX_OUT_BYTES { - return None; - } - } - Some(()) -} - -/// Known operator names written upright in a run (`sin`, `log`, `lim`). -const FUNCTIONS: &[&str] = &[ - "sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "log", "ln", "lg", "exp", "lim", "max", "min", - "sup", "inf", "det", "gcd", "deg", "dim", "ker", "arg", "Pr", "liminf", "limsup", -]; - -fn run(r: &El, out: &mut String) -> Option<()> { - let text = run_text(r); - if text.is_empty() { - return Some(()); - } - let rpr = r.child("rPr"); - if on(rpr, "nor") { - out.push_str("\\text{"); - escape_text(&text, out)?; - out.push('}'); - return Some(()); - } - let plain = val(rpr, "sty") == Some("p"); - if plain && FUNCTIONS.contains(&text.trim()) { - out.push('\\'); - out.push_str(text.trim()); - out.push(' '); - return Some(()); - } - let wrap = match (val(rpr, "scr"), val(rpr, "sty")) { - (Some("double-struck"), _) => Some("\\mathbb{"), - (Some("script"), _) => Some("\\mathcal{"), - (Some("fraktur"), _) => Some("\\mathfrak{"), - (Some("sans-serif"), _) => Some("\\mathsf{"), - (Some("monospace"), _) => Some("\\mathtt{"), - (_, Some("b")) => Some("\\mathbf{"), - (_, Some("bi")) => Some("\\boldsymbol{"), - (_, Some("p")) if text.chars().any(|c| c.is_alphabetic()) => Some("\\mathrm{"), - _ => None, - }; - if let Some(w) = wrap { - out.push_str(w); - } - for c in text.chars() { - match char_latex(c) { - Some(l) => out.push_str(l), - None => out.push(c), - } - // Checked per character, not from the run's byte length: a character may map to a - // longer macro or a shorter sign, so only the LaTeX produced counts. - if out.len() > MAX_OUT_BYTES { - return None; - } - } - if wrap.is_some() { - out.push('}'); - } - Some(()) -} - -/// A delimiter character as a `\left`/`\right` argument. -fn delim(c: Option<&str>, default: &str) -> String { - let c = c.unwrap_or(default); - match c { - "" => ".".into(), - "{" => "\\{".into(), - "}" => "\\}".into(), - "⟨" | "〈" => "\\langle".into(), - "⟩" | "〉" => "\\rangle".into(), - "⌊" => "\\lfloor".into(), - "⌋" => "\\rfloor".into(), - "⌈" => "\\lceil".into(), - "⌉" => "\\rceil".into(), - "‖" => "\\|".into(), - "∣" => "|".into(), - other => other.into(), - } -} - -fn nary_op(chr: &str) -> Option<&'static str> { - Some(match chr { - "∑" => "\\sum", - "∏" => "\\prod", - "∐" => "\\coprod", - "∫" => "\\int", - "∬" => "\\iint", - "∭" => "\\iiint", - "∮" => "\\oint", - "⋃" => "\\bigcup", - "⋂" => "\\bigcap", - "⋁" => "\\bigvee", - "⋀" => "\\bigwedge", - "⨁" => "\\bigoplus", - "⨂" => "\\bigotimes", - _ => return None, - }) -} - -fn accent(chr: &str) -> Option<&'static str> { - Some(match chr { - "\u{0302}" | "^" => "\\hat", - "\u{030C}" => "\\check", - "\u{0303}" | "~" => "\\tilde", - "\u{0301}" => "\\acute", - "\u{0300}" => "\\grave", - "\u{0307}" => "\\dot", - "\u{0308}" => "\\ddot", - "\u{0306}" => "\\breve", - "\u{0305}" | "\u{0304}" | "¯" => "\\bar", - "\u{20D7}" | "→" => "\\vec", - "\u{20D6}" => "\\overleftarrow", - "\u{030A}" => "\\mathring", - _ => return None, - }) -} - -fn node(e: &El, out: &mut String, depth: usize) -> Option<()> { - if depth > MAX_DEPTH { - return None; - } - match e.name.as_str() { - // Properties and run-level DrawingML are not content. - n if n.ends_with("Pr") => {} - "r" => run(e, out)?, - "f" => fraction(e, out, depth)?, - "rad" => radical(e, out, depth)?, - "sSup" | "sSub" | "sSubSup" => scripts(e, out, depth)?, - "nary" => nary(e, out, depth)?, - "d" => delimiters(e, out, depth)?, - "m" => matrix(e, out, depth)?, - "eqArr" => equation_array(e, out, depth)?, - "acc" => { - out.push_str(accent(val(e.child("accPr"), "chr").unwrap_or("\u{0302}"))?); - group(e.child("e"), out, depth)?; - } - "bar" => { - out.push_str(if val(e.child("barPr"), "pos") == Some("top") { "\\overline" } else { "\\underline" }); - group(e.child("e"), out, depth)?; - } - "groupChr" => group_char(e, out, depth)?, - "limLow" | "limUpp" => limit(e, out, depth)?, - "func" => { - seq(e.child("fName")?, out, depth)?; - out.push(' '); - group(e.child("e"), out, depth)?; - } - "borderBox" => { - out.push_str("\\boxed"); - group(e.child("e"), out, depth)?; - } - "phant" => { - out.push_str("\\phantom"); - group(e.child("e"), out, depth)?; - } - "box" => group(e.child("e"), out, depth)?, - _ => return None, - } - Some(()) -} - -/// `m:f`: a fraction, or a binomial-style stack without a bar. -fn fraction(e: &El, out: &mut String, depth: usize) -> Option<()> { - if val(e.child("fPr"), "type") == Some("noBar") { - out.push_str("\\genfrac{}{}{0pt}{}"); - } else { - out.push_str("\\frac"); - } - group(e.child("num"), out, depth)?; - group(e.child("den"), out, depth) -} - -/// `m:rad`: a square root, or a root with a degree. -fn radical(e: &El, out: &mut String, depth: usize) -> Option<()> { - let hide = on(e.child("radPr"), "degHide"); - match e.child("deg").filter(|d| !hide && !d.children.is_empty()) { - Some(d) => { - out.push_str("\\sqrt["); - seq(d, out, depth)?; - out.push(']'); - } - None => out.push_str("\\sqrt"), - } - group(e.child("e"), out, depth) -} - -/// `m:sSup`, `m:sSub`, `m:sSubSup`: a base with scripts. -fn scripts(e: &El, out: &mut String, depth: usize) -> Option<()> { - group(e.child("e"), out, depth)?; - if let Some(sub) = e.child("sub") { - out.push('_'); - group(Some(sub), out, depth)?; - } - if let Some(sup) = e.child("sup") { - out.push('^'); - group(Some(sup), out, depth)?; - } - Some(()) -} - -/// `m:nary`: a large operator with its limits and operand. -fn nary(e: &El, out: &mut String, depth: usize) -> Option<()> { - let p = e.child("naryPr"); - let op = nary_op(val(p, "chr").unwrap_or("∫"))?; - out.push_str(op); - if val(p, "limLoc") == Some("undOvr") && op.contains("int") { - out.push_str("\\limits"); - } - if !on(p, "subHide") { - out.push('_'); - group(e.child("sub"), out, depth)?; - } - if !on(p, "supHide") { - out.push('^'); - group(e.child("sup"), out, depth)?; - } - out.push(' '); - group(e.child("e"), out, depth) -} - -/// `m:d`: delimiters around one or more parts, with a separator between them. -fn delimiters(e: &El, out: &mut String, depth: usize) -> Option<()> { - let p = e.child("dPr"); - out.push_str("\\left"); - out.push_str(&delim(val(p, "begChr"), "(")); - out.push(' '); - let sep = delim(val(p, "sepChr"), "|"); - for (i, part) in e.kids("e").enumerate() { - if i > 0 { - out.push_str(" \\middle"); - out.push_str(&sep); - out.push(' '); - } - seq(part, out, depth)?; - } - out.push_str(" \\right"); - out.push_str(&delim(val(p, "endChr"), ")")); - Some(()) -} - -/// `m:m`: a matrix, row by row. -fn matrix(e: &El, out: &mut String, depth: usize) -> Option<()> { - out.push_str("\\begin{matrix}"); - for (i, row) in e.kids("mr").enumerate() { - if i > 0 { - out.push_str(" \\\\ "); - } - for (k, cell) in row.kids("e").enumerate() { - if k > 0 { - out.push_str(" & "); - } - seq(cell, out, depth)?; - } - } - out.push_str("\\end{matrix}"); - Some(()) -} - -/// `m:eqArr`: equations stacked one per row. -fn equation_array(e: &El, out: &mut String, depth: usize) -> Option<()> { - out.push_str("\\begin{gathered}"); - for (i, row) in e.kids("e").enumerate() { - if i > 0 { - out.push_str(" \\\\ "); - } - seq(row, out, depth)?; - } - out.push_str("\\end{gathered}"); - Some(()) -} - -/// Effective brace orientation, including the character default and its precedence over position. -fn group_char_is_over(e: &El) -> bool { - let p = e.child("groupChrPr"); - match val(p, "chr").unwrap_or("\u{23DF}") { - "\u{23DE}" => true, - "\u{23DF}" => false, - _ => val(p, "pos") == Some("top"), - } -} - -/// `m:groupChr`: a brace over or under its content. -fn group_char(e: &El, out: &mut String, depth: usize) -> Option<()> { - out.push_str(if group_char_is_over(e) { "\\overbrace" } else { "\\underbrace" }); - group(e.child("e"), out, depth) -} - -/// `m:limLow`, `m:limUpp`: a limit under or over its base. -fn limit(e: &El, out: &mut String, depth: usize) -> Option<()> { - let low = e.name == "limLow"; - let base = e.child("e"); - // A function name with a limit (lim, max) takes it as a subscript with \limits. - let base_is_fn = base.is_some_and(|b| { - let t: String = b.kids("r").map(run_text).collect(); - b.children.iter().all(|c| c.name == "r") && FUNCTIONS.contains(&t.trim()) - }); - // A brace alone under the limit is a labelled brace, as `gridcraft_math::to_omml` writes - // `\underbrace{x}_{n}` and `\overbrace{x}^{n}`: the label is the brace's own script, below - // for an underbrace and above for an overbrace. An opposite-side limit keeps its placement. - let brace = base - .and_then(|b| { - let mut content = b.children.iter().filter(|c| !c.name.ends_with("Pr")); - content.next().filter(|c| c.name == "groupChr" && content.next().is_none()) - }) - .filter(|brace| low != group_char_is_over(brace)); - if base_is_fn { - seq(base?, out, depth)?; - out.push_str(if low { "\\limits_" } else { "\\limits^" }); - group(e.child("lim"), out, depth)?; - } else if let Some(brace) = brace { - group_char(brace, out, depth + 1)?; - out.push(if low { '_' } else { '^' }); - group(e.child("lim"), out, depth)?; - } else { - out.push_str(if low { "\\underset" } else { "\\overset" }); - group(e.child("lim"), out, depth)?; - group(base, out, depth)?; - } - Some(()) -} - #[cfg(test)] mod tests { use super::*; @@ -673,6 +299,29 @@ mod tests { to_latex(&el(xml)) } + #[test] + fn conversion_does_not_accept_a_partial_equation() { + assert_eq!(latex("x"), None); + assert_eq!( + latex( + "xy" + ), + None + ); + assert_eq!(latex("x^2"), None); + assert_eq!(latex("x2").as_deref(), Some("{x}^{2}")); + let cells = "x".repeat(65); + assert_eq!(latex(&format!("{cells}")), None); + } + + #[test] + fn literal_run_property_invalidates_the_saved_source_marker() { + let plain = el("x"); + let literal = el("x"); + assert_ne!(body_marker(&plain), body_marker(&literal)); + assert_eq!(body_marker(&plain), body_marker(&plain.clone())); + } + #[test] fn the_subset_reads_back() { assert_eq!(latex("x+1").as_deref(), Some("x+1")); @@ -685,13 +334,13 @@ mod tests { let sum = latex( "i=1ni", ); - assert_eq!(sum.as_deref(), Some("\\sum_{i=1}^{n} {i}")); + assert_eq!(sum.as_deref(), Some("\\sum\\limits_{i=1}^{n} {i}")); // An integral without a character, with hidden limits. assert_eq!(latex("f").as_deref(), Some("\\int {f}")); let m = latex( "1001", ); - assert_eq!(m.as_deref(), Some("\\left[ \\begin{matrix}1 & 0 \\\\ 0 & 1\\end{matrix} \\right]")); + assert_eq!(m.as_deref(), Some("\\left[\\begin{matrix}1&0\\\\0&1\\end{matrix}\\right]")); assert_eq!(latex("sinx").as_deref(), Some("\\sin x")); assert_eq!(latex("R").as_deref(), Some("\\mathbb{R}")); assert_eq!(latex("if {x}").as_deref(), Some("\\text{if \\{x\\}}")); @@ -703,9 +352,9 @@ mod tests { #[test] fn what_is_outside_the_subset_is_none() { - assert_eq!(latex(""), None); + assert_eq!(latex("").as_deref(), Some("{}_{}^{}{}")); assert_eq!(latex(""), None, "an empty equation is not maths"); - assert_eq!(latex(""), None); + assert_eq!(latex("").as_deref(), Some("☃ {}")); // Deep nesting stops instead of recursing without bound. let deep = format!("{}x{}", "".repeat(100), "".repeat(100)); assert_eq!(latex(&deep), None); @@ -719,22 +368,21 @@ mod tests { // refusing it, so the caller falls back to the writer's text in bounded time. let wide = el(&"x".repeat(100_000)); let start = std::time::Instant::now(); - assert_eq!(convert(&wide), None); assert_eq!(to_latex(&wide), None); assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); // One run whose text alone is past the cap is refused before it is escaped (each // backslash would otherwise grow to `\textbackslash `). - let long = el(&format!("{}", "\\".repeat(MAX_OUT_BYTES + 1))); - assert_eq!(convert(&long), None); + let long = el(&format!("{}", "\\".repeat(gridcraft_math::MAX_SOURCE_BYTES + 1))); + assert_eq!(to_latex(&long), None); // Groups count the braces they add even when no run adds text. - let groups = el(&"".repeat(MAX_OUT_BYTES / 2 + 1)); - assert_eq!(convert(&groups), None); + let groups = el(&"".repeat(gridcraft_math::MAX_SOURCE_BYTES / 2 + 1)); + assert_eq!(to_latex(&groups), None); // At the cap the equation still reads back, and the cap counts the LaTeX produced, not // the run's bytes: a minus sign (three bytes of UTF-8) becomes a one-byte `-`. - let at_cap = el(&"x".repeat(MAX_OUT_BYTES)); - assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(MAX_OUT_BYTES)); - let minus = el(&format!("{}", "\u{2212}".repeat(MAX_OUT_BYTES))); - assert_eq!(to_latex(&minus), Some("-".repeat(MAX_OUT_BYTES))); + let at_cap = el(&"x".repeat(gridcraft_math::MAX_SOURCE_BYTES)); + assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(gridcraft_math::MAX_SOURCE_BYTES)); + let minus = el(&format!("{}", "\u{2212}".repeat(gridcraft_math::MAX_SOURCE_BYTES))); + assert_eq!(to_latex(&minus), Some("-".repeat(gridcraft_math::MAX_SOURCE_BYTES))); } #[test] @@ -764,17 +412,17 @@ mod tests { #[test] fn a_limit_on_the_opposite_side_of_a_brace_keeps_its_placement() { - for (properties, brace, opposite, same, script) in [ - (r#""#, "underbrace", "limUpp", "limLow", '_'), - (r#""#, "overbrace", "limLow", "limUpp", '^'), - (r#""#, "underbrace", "limUpp", "limLow", '_'), - (r#""#, "overbrace", "limLow", "limUpp", '^'), + for (properties, brace, opposite, same) in [ + (r#""#, "overbrace", "limUpp", "limLow"), + (r#""#, "underbrace", "limLow", "limUpp"), + (r#""#, "overbrace", "limUpp", "limLow"), + (r#""#, "overbrace", "limLow", "limUpp"), ] { let base = format!("{properties}x"); let limit = |kind: &str| format!("{base}n"); - let placement = if opposite == "limLow" { "underset" } else { "overset" }; - assert_eq!(latex(&limit(opposite)), Some(format!("\\{placement}{{n}}{{\\{brace}{{x}}}}")), "{properties}"); - assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{script}{{n}}")), "{properties}"); + let script = |kind: &str| if kind == "limUpp" { '^' } else { '_' }; + assert_eq!(latex(&limit(opposite)), Some(format!("\\{brace}{{x}}{}{{n}}", script(opposite))), "{properties}"); + assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{}{{n}}", script(same))), "{properties}"); } } diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index d406c01346..35fd4c8818 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -8,7 +8,7 @@ use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRe use gridcraft_formula::Expr; use gridcraft_model::{ AutoFilter, Cell, CfOperator, CfRule, CfValueKind, Comment, CondFormat, EditRange, ErrorStyle, FilterCriterion, Formula, Hyperlink, LineInfo, - NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Table, TableColumn, TotalsFn, + NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Style, Table, TableColumn, TotalsFn, Validation, ValidationKind, XmlColumnPr, }; @@ -25,7 +25,7 @@ mod rules; pub use parts::{read_autofilter, read_table}; use parts::{read_comments, read_hyperlinks, read_note_shapes, read_threaded}; -use rules::{read_cf, read_validation}; +use rules::{read_cf, read_validation, read_x14_cf}; struct Shared { anchor: CellRef, @@ -344,7 +344,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "extLst" => read_ext(cx, e, &mut sheet), + "extLst" => read_ext(cx, e, &mut sheet, &mut cf_kept_cells), "protectedRanges" => read_protected_ranges(e, &mut sheet), _ => {} } @@ -850,7 +850,7 @@ pub fn parse_sqref(s: Option<&str>) -> Vec { } /// Worksheet extensions: x14 data validations and sparklines. -fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { +fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, cf_kept_cells: &mut u64) { for ext in e.kids("ext") { for c in &ext.children { match c.name.as_str() { @@ -878,23 +878,7 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { } } } - "conditionalFormattings" => { - let mut skipped = false; - for r in c.kids("conditionalFormatting").flat_map(|f| f.kids("cfRule")) { - let idx = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id)).map(|(_, n)| *n); - match (idx.and_then(|n| sheet.cond_formats.get_mut(n)), r.child("dataBar")) { - (Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => { - *gradient = db.flag("gradient", true); - // Only the fill style is modelled; borders, lengths, axis or negative colours are lost. - skipped |= db.attrs.iter().any(|(k, _)| k != "gradient") || db.children.iter().any(|k| k.name != "cfvo"); - } - _ => skipped = true, - } - } - if skipped { - cx.warn("some Excel 2010 conditional format extensions were skipped"); - } - } + "conditionalFormattings" => read_x14_cf(cx, c, sheet, cf_kept_cells), _ => {} } } diff --git a/crates/xlsx/src/sheet_read/rules.rs b/crates/xlsx/src/sheet_read/rules.rs index c3a3f04f65..b985953c9c 100644 --- a/crates/xlsx/src/sheet_read/rules.rs +++ b/crates/xlsx/src/sheet_read/rules.rs @@ -1,5 +1,5 @@ use super::{ - CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Validation, ValidationKind, from_file, + CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Style, Validation, ValidationKind, from_file, parse_sqref, read_color, }; @@ -57,79 +57,164 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: & for r in e.kids("cfRule") { let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default()); let formulas: Vec = r.kids("formula").map(|f| from_file(f.text.trim())).collect(); - let f0 = formulas.first().cloned().unwrap_or_default(); - let text = r.attr("text").unwrap_or("").to_string(); // The x14 id that links a data bar to its Excel 2010 extension (solid fill lives there). let ext_id = r.child("extLst").and_then(|l| l.kids("ext").find_map(|x| x.child("id"))).map(|i| i.text.trim().to_string()).filter(|i| !i.is_empty()); - let rule = match r.attr("type").unwrap_or("") { - "cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.get(1).cloned(), style }, - "expression" => CfRule::Expression { formula: f0, style }, - "containsText" => CfRule::ContainsText { text, style }, - "notContainsText" => CfRule::NotContainsText { text, style }, - "beginsWith" => CfRule::BeginsWith { text, style }, - "endsWith" => CfRule::EndsWith { text, style }, - "containsBlanks" => CfRule::Blanks { style }, - "notContainsBlanks" => CfRule::NoBlanks { style }, - "containsErrors" => CfRule::Errors { style }, - "notContainsErrors" => CfRule::NoErrors { style }, - "duplicateValues" => CfRule::Duplicate { style }, - "uniqueValues" => CfRule::Unique { style }, - "top10" => { - CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style } - } - "aboveAverage" => CfRule::AboveAverage { - below: !r.flag("aboveAverage", true), - equal: r.flag("equalAverage", false), - std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8, - style, - }, - "timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style }, - "colorScale" => { - let Some(cs) = r.child("colorScale") else { continue }; - let colors = cs.kids("color").map(|c| read_color(c, &cx.palette)); - CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() } - } - "dataBar" => { - let Some(db) = r.child("dataBar") else { continue }; - let v = cfvos(db); - CfRule::DataBar { - min: v.first().cloned().unwrap_or(CfValueKind::Min), - max: v.get(1).cloned().unwrap_or(CfValueKind::Max), - color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(), - gradient: true, - show_value: db.flag("showValue", true), + let ty = r.attr("type").unwrap_or(""); + match cf_rule(cx, r, ty, formulas, style) { + Some(rule) => { + if !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells) { + break; + } + if let Some(id) = ext_id { + cx.cf_ext_ids.push((id, sheet.cond_formats.len() - 1)); } } - "iconSet" => { - let Some(is) = r.child("iconSet") else { continue }; - CfRule::IconSet { - set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(), - thresholds: cfvos(is), - reverse: is.flag("reverse", false), - show_value: is.flag("showValue", true), - } + None if matches!(ty, "colorScale" | "dataBar" | "iconSet") => {} + None => cx.warn(format!("conditional format type \"{ty}\" is not supported")), + } + } +} + +fn push_cf(cx: &mut Ctx<'_>, sheet: &mut Sheet, ranges: &[RangeRef], block_cells: u64, r: &El, rule: CfRule, kept_cells: &mut u64) -> bool { + let total = kept_cells.saturating_add(block_cells); + if total > MAX_COND_CELLS { + cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped")); + return false; + } + *kept_cells = total; + sheet.cond_formats.push(CondFormat { + ranges: ranges.to_vec(), + rule, + priority: r.attr_u32("priority").unwrap_or(0), + stop_if_true: r.flag("stopIfTrue", false), + }); + true +} + +/// The rule of a `cfRule` (main namespace or x14) of type `ty`, given its formulas and +/// differential style; `None` for an unknown type or a scale, bar or icon set without its body. +fn cf_rule(cx: &Ctx<'_>, r: &El, ty: &str, formulas: Vec, style: Box