mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-28 17:30:24 +01:00
Merge branch 'main' of https://github.com/storytold/gridcraft into HEAD
# Conflicts: # crates/engine/src/cmd/print/objects.rs
This commit is contained in:
commit
9e1abd22a2
56 files changed
+3119
-1394
No files matched your search
Generated
+110
-13
@@ -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",
|
||||
|
||||
+4
-1
@@ -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"
|
||||
|
||||
+5
-1
@@ -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, `<controls>` 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) |
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<RangeRef>,
|
||||
/// One name cell per series, in the line beside `values`, when every series has one there.
|
||||
pub names: Option<RangeRef>,
|
||||
}
|
||||
|
||||
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<RangeRef> {
|
||||
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<ChartData> {
|
||||
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<Vec<CellRef>> = 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<Chart, ValuesError> {
|
||||
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)
|
||||
}
|
||||
@@ -96,6 +96,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
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);
|
||||
|
||||
@@ -95,6 +95,7 @@ fn insert_equation(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
text: latex.to_string(),
|
||||
format: Default::default(),
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
};
|
||||
shape.math.refresh(latex);
|
||||
let sheet = d.wb.active_sheet();
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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!(
|
||||
|
||||
@@ -233,6 +233,38 @@ pub(super) fn select_data(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<Json> {
|
||||
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<Json> {
|
||||
let (si, ci) = find_chart(s, p)?;
|
||||
let target = match p.get("sheet").and_then(Json::as_str) {
|
||||
|
||||
@@ -164,7 +164,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -358,6 +358,7 @@ pub(super) fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
line: Color::Auto,
|
||||
text: name,
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
};
|
||||
let sheet = d.wb.active_sheet();
|
||||
|
||||
@@ -163,6 +163,7 @@ pub(super) fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
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<Json> {
|
||||
pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
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<Json> {
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -194,6 +194,7 @@ fn insert_word_art(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
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.
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
pub mod catalog;
|
||||
pub mod cf;
|
||||
pub mod chart_data;
|
||||
mod chart_svg;
|
||||
mod clip_html;
|
||||
pub mod cmd;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ChartData> {
|
||||
chart_data(&s.doc().unwrap().wb, 0, &chart(s))
|
||||
}
|
||||
|
||||
/// Points each plotted series has, as the chart resolves them.
|
||||
fn points(s: &Session) -> Vec<usize> {
|
||||
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::<Color>, "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}");
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -218,21 +218,85 @@ fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R<f64> {
|
||||
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<f64> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -946,6 +946,7 @@ mod tests {
|
||||
fill: Color::default(),
|
||||
line: Color::default(),
|
||||
text: String::new(),
|
||||
rotation: 0.0,
|
||||
format: ShapeFormat::default(),
|
||||
math: EquationCache::default(),
|
||||
}),
|
||||
|
||||
+182
-12
@@ -298,9 +298,12 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
|
||||
return painted;
|
||||
}
|
||||
// Source outlines stay in cell space beneath every floating object.
|
||||
if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart() == Some(ch.id))
|
||||
if let Some((_, data)) = selected_chart_data(app, geo, wb, si, sh, p.clip_rect()) {
|
||||
paint_chart_data(p, geo, sh, &data);
|
||||
} else if let Some(ch) = sh.charts.iter().find(|ch| app.selected_chart() == Some(ch.id))
|
||||
&& anchor_rect(geo, sh, &ch.anchor).intersects(p.clip_rect())
|
||||
{
|
||||
// Series that are not one block of cells: each series' values on this sheet.
|
||||
for s in &ch.series {
|
||||
if let Ok(gridcraft_engine::formula::Expr::Ref(rf)) = gridcraft_engine::formula::parse(&s.values)
|
||||
&& rf.sheet_name().is_none_or(|n| n.eq_ignore_ascii_case(&sh.name))
|
||||
@@ -385,6 +388,9 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
|
||||
if label && !sp.text.is_empty() && !app.editing_text_box(sp.id) {
|
||||
paint_shape_text(p, wb, sp, r, geo.z);
|
||||
}
|
||||
if sp.rotation != 0.0 {
|
||||
turn_painted(p, start, r.center(), sp.rotation);
|
||||
}
|
||||
done(start, r);
|
||||
}
|
||||
for im in &sh.images {
|
||||
@@ -428,11 +434,13 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
|
||||
}
|
||||
// The selected object's frame and handles go over every object, and move with it on a
|
||||
// right-to-left sheet.
|
||||
if let Some(r) = app.selected_object.and_then(|o| object_rect(geo, sh, o))
|
||||
if let Some(o) = app.selected_object
|
||||
&& let Some(r) = object_rect(geo, sh, o)
|
||||
&& r.intersects(p.clip_rect())
|
||||
{
|
||||
let start = p.add(egui::Shape::Noop);
|
||||
selection_frame(p, r);
|
||||
let (deg, rotates, resizes) = frame_of(sh, o);
|
||||
crate::frame::paint(p, r, deg, rotates, resizes);
|
||||
done(start, r);
|
||||
}
|
||||
painted
|
||||
@@ -540,16 +548,97 @@ pub fn slicer_click(geo: &Geo, sh: &Sheet, wb: &Workbook, si: usize, p: Pos2) ->
|
||||
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<Rect> {
|
||||
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<Pos2> {
|
||||
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;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<Item = Handle> {
|
||||
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<Grab> {
|
||||
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<Pos2> = (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);
|
||||
}
|
||||
}
|
||||
@@ -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<RangeRef>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The fill a left-drag of the handle just made, which the Auto Fill Options button can redo
|
||||
|
||||
@@ -57,7 +57,8 @@ fn drag_cursor(drag: &Drag, rtl: bool) -> Option<CursorIcon> {
|
||||
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);
|
||||
|
||||
@@ -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<u32> {
|
||||
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)];
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -227,7 +227,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
// 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<Shape> {
|
||||
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::<f64>().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::<String>()).collect::<Vec<_>>().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}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{}\" cy=\"{}\"/></{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}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{}\" cy=\"{}\"/></{tag}>", e(a.width), e(a.height))
|
||||
}
|
||||
|
||||
pub fn srgb(c: &Color, theme: &Theme) -> Option<String> {
|
||||
@@ -545,7 +608,7 @@ pub fn write_drawing(sheet: &Sheet, theme: &Theme, objs: &[Obj<'_>]) -> String {
|
||||
"<xdr:sp macro=\"\" textlink=\"\"><xdr:nvSpPr><xdr:cNvPr id=\"{id}\" name=\"Shape {}\"/><xdr:cNvSpPr{}/></xdr:nvSpPr><xdr:spPr>{}<a:prstGeom prst=\"{prst}\"><a:avLst/></a:prstGeom>",
|
||||
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, "<a:solidFill>{c}</a:solidFill>");
|
||||
@@ -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#"<txBody><p><rPr><t>hidden</t></rPr><r><t>before </t></r><AlternateContent><Choice><r><t>choice</t></r></Choice><Fallback><r><t>fallback</t></r></Fallback></AlternateContent><r><t> after</t></r></p><p><r><t>next</t></r></p></txBody>"#).unwrap();
|
||||
assert_eq!(math_body_text(&tb), "before fallback after\nnext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_output_cap_keeps_utf8_intact() {
|
||||
let xml = format!("<txBody><p><r><t>a{}</t></r></p></txBody>", "λ".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('λ'));
|
||||
}
|
||||
}
|
||||
@@ -187,6 +187,7 @@ pub(super) fn read(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
line,
|
||||
text,
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
+96
-628
@@ -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:
|
||||
//! <https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part3-schema/OpenDocument-v1.3-os-part3-schema.html>.
|
||||
//! 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<Option<String>, 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<String>, default: u32, limit: u32) -> Result<u32, IoError> {
|
||||
let n = match value {
|
||||
Some(s) => s.parse::<u32>().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<RepeatedCell>,
|
||||
}
|
||||
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<String>,
|
||||
raw: Option<String>,
|
||||
formula: bool,
|
||||
text: String,
|
||||
paragraph: Option<usize>,
|
||||
paragraphs: usize,
|
||||
paragraph_started: bool,
|
||||
pending_space: bool,
|
||||
}
|
||||
struct Import {
|
||||
wb: Workbook,
|
||||
report: ReadReport,
|
||||
stack: Vec<Tag>,
|
||||
sheet: Option<SheetDraft>,
|
||||
row: Option<RowDraft>,
|
||||
cell: Option<CellDraft>,
|
||||
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::<u32>()).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::<f64>().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<f64> {
|
||||
match s.split_once('.') {
|
||||
Some((a, b)) => {
|
||||
digits(a)?;
|
||||
digits(b)?;
|
||||
}
|
||||
None => {
|
||||
digits(s)?;
|
||||
}
|
||||
}
|
||||
s.parse::<f64>().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<f64> {
|
||||
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::<f64>().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::<f64>().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 })
|
||||
}
|
||||
+159
-511
@@ -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<String> {
|
||||
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<String> {
|
||||
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("<m:");
|
||||
out.push_str(&e.name);
|
||||
for (k, v) in &e.attrs {
|
||||
out.push(' ');
|
||||
if k == "val" {
|
||||
out.push_str("m:val");
|
||||
} else {
|
||||
out.push_str(k);
|
||||
}
|
||||
"oMath" => 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("</m:");
|
||||
out.push_str(&e.name);
|
||||
out.push('>');
|
||||
}
|
||||
|
||||
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("<m:r><m:t>x</m:t></m:r><m:unknown/>"), None);
|
||||
assert_eq!(
|
||||
latex(
|
||||
"<m:r><m:t>x</m:t></m:r><mc:AlternateContent xmlns:mc=\"mc\"><mc:Fallback><m:r><m:t>y</m:t></m:r></mc:Fallback></mc:AlternateContent>"
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(latex("<m:r><m:t>x^2</m:t></m:r>"), None);
|
||||
assert_eq!(latex("<m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>").as_deref(), Some("{x}^{2}"));
|
||||
let cells = "<m:e><m:r><m:t>x</m:t></m:r></m:e>".repeat(65);
|
||||
assert_eq!(latex(&format!("<m:m><m:mr>{cells}</m:mr></m:m>")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_run_property_invalidates_the_saved_source_marker() {
|
||||
let plain = el("<m:r><m:t>x</m:t></m:r>");
|
||||
let literal = el("<m:r><m:rPr><m:lit/></m:rPr><m:t>x</m:t></m:r>");
|
||||
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("<m:r><m:t>x+1</m:t></m:r>").as_deref(), Some("x+1"));
|
||||
@@ -685,13 +334,13 @@ mod tests {
|
||||
let sum = latex(
|
||||
"<m:nary><m:naryPr><m:chr m:val=\"∑\"/><m:limLoc m:val=\"undOvr\"/></m:naryPr><m:sub><m:r><m:t>i=1</m:t></m:r></m:sub><m:sup><m:r><m:t>n</m:t></m:r></m:sup><m:e><m:r><m:t>i</m:t></m:r></m:e></m:nary>",
|
||||
);
|
||||
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("<m:nary><m:naryPr><m:subHide m:val=\"1\"/><m:supHide m:val=\"1\"/></m:naryPr><m:sub/><m:sup/><m:e><m:r><m:t>f</m:t></m:r></m:e></m:nary>").as_deref(), Some("\\int {f}"));
|
||||
let m = latex(
|
||||
"<m:d><m:dPr><m:begChr m:val=\"[\"/><m:endChr m:val=\"]\"/></m:dPr><m:e><m:m><m:mr><m:e><m:r><m:t>1</m:t></m:r></m:e><m:e><m:r><m:t>0</m:t></m:r></m:e></m:mr><m:mr><m:e><m:r><m:t>0</m:t></m:r></m:e><m:e><m:r><m:t>1</m:t></m:r></m:e></m:mr></m:m></m:e></m:d>",
|
||||
);
|
||||
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("<m:r><m:rPr><m:sty m:val=\"p\"/></m:rPr><m:t>sin</m:t></m:r><m:r><m:t>x</m:t></m:r>").as_deref(), Some("\\sin x"));
|
||||
assert_eq!(latex("<m:r><m:rPr><m:scr m:val=\"double-struck\"/></m:rPr><m:t>R</m:t></m:r>").as_deref(), Some("\\mathbb{R}"));
|
||||
assert_eq!(latex("<m:r><m:rPr><m:nor/></m:rPr><m:t>if {x}</m:t></m:r>").as_deref(), Some("\\text{if \\{x\\}}"));
|
||||
@@ -703,9 +352,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn what_is_outside_the_subset_is_none() {
|
||||
assert_eq!(latex("<m:sPre><m:sub/><m:sup/><m:e/></m:sPre>"), None);
|
||||
assert_eq!(latex("<m:sPre><m:sub/><m:sup/><m:e/></m:sPre>").as_deref(), Some("{}_{}^{}{}"));
|
||||
assert_eq!(latex(""), None, "an empty equation is not maths");
|
||||
assert_eq!(latex("<m:nary><m:naryPr><m:chr m:val=\"☃\"/></m:naryPr><m:e/></m:nary>"), None);
|
||||
assert_eq!(latex("<m:nary><m:naryPr><m:chr m:val=\"☃\"/></m:naryPr><m:e/></m:nary>").as_deref(), Some("☃ {}"));
|
||||
// Deep nesting stops instead of recursing without bound.
|
||||
let deep = format!("{}<m:r><m:t>x</m:t></m:r>{}", "<m:box><m:e>".repeat(100), "</m:e></m:box>".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(&"<m:r><m:t>x</m:t></m:r>".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!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{}</m:t></m:r>", "\\".repeat(MAX_OUT_BYTES + 1)));
|
||||
assert_eq!(convert(&long), None);
|
||||
let long = el(&format!("<m:r><m:rPr><m:nor/></m:rPr><m:t>{}</m:t></m:r>", "\\".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(&"<m:box><m:e/></m:box>".repeat(MAX_OUT_BYTES / 2 + 1));
|
||||
assert_eq!(convert(&groups), None);
|
||||
let groups = el(&"<m:box><m:e/></m:box>".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(&"<m:r><m:t>x</m:t></m:r>".repeat(MAX_OUT_BYTES));
|
||||
assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(MAX_OUT_BYTES));
|
||||
let minus = el(&format!("<m:r><m:t>{}</m:t></m:r>", "\u{2212}".repeat(MAX_OUT_BYTES)));
|
||||
assert_eq!(to_latex(&minus), Some("-".repeat(MAX_OUT_BYTES)));
|
||||
let at_cap = el(&"<m:r><m:t>x</m:t></m:r>".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!("<m:r><m:t>{}</m:t></m:r>", "\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#"<m:chr m:val="⏟"/><m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
|
||||
(r#"<m:chr m:val="⏞"/><m:pos m:val="bot"/>"#, "overbrace", "limLow", "limUpp", '^'),
|
||||
(r#"<m:pos m:val="top"/>"#, "underbrace", "limUpp", "limLow", '_'),
|
||||
(r#"<m:chr m:val="?"/><m:pos m:val="top"/>"#, "overbrace", "limLow", "limUpp", '^'),
|
||||
for (properties, brace, opposite, same) in [
|
||||
(r#"<m:chr m:val="⏟"/><m:pos m:val="top"/>"#, "overbrace", "limUpp", "limLow"),
|
||||
(r#"<m:chr m:val="⏞"/><m:pos m:val="bot"/>"#, "underbrace", "limLow", "limUpp"),
|
||||
(r#"<m:pos m:val="top"/>"#, "overbrace", "limUpp", "limLow"),
|
||||
(r#"<m:chr m:val="?"/><m:pos m:val="top"/>"#, "overbrace", "limLow", "limUpp"),
|
||||
] {
|
||||
let base = format!("<m:groupChr><m:groupChrPr>{properties}</m:groupChrPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:groupChr>");
|
||||
let limit = |kind: &str| format!("<m:{kind}><m:e>{base}</m:e><m:lim><m:r><m:t>n</m:t></m:r></m:lim></m:{kind}>");
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<RangeRef> {
|
||||
}
|
||||
|
||||
/// 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),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String> = 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<String>, style: Box<Style>) -> Option<CfRule> {
|
||||
let mut formulas = formulas.into_iter();
|
||||
let f0 = formulas.next().unwrap_or_default();
|
||||
let text = r.attr("text").unwrap_or("").to_string();
|
||||
Some(match ty {
|
||||
"cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.next(), 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 cs = r.child("colorScale")?;
|
||||
let colors = cs.kids("color").map(|c| read_color(c, &cx.palette));
|
||||
CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() }
|
||||
}
|
||||
"dataBar" => {
|
||||
let db = r.child("dataBar")?;
|
||||
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),
|
||||
}
|
||||
other => {
|
||||
cx.warn(format!("conditional format type \"{other}\" is not supported"));
|
||||
}
|
||||
"iconSet" => {
|
||||
let is = r.child("iconSet")?;
|
||||
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),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `x14:conditionalFormattings` (MS-XLSX 2.4.6): rules kept out of the main section, such as
|
||||
/// those whose formulas refer to other sheets in the one LibreOffice-saved file seen. They carry
|
||||
/// `xm:f` formulas, an inline `x14:dxf` and priorities shared with the main-section rules.
|
||||
/// Read: cellIs, expression, (not)containsBlanks, (not)containsErrors, duplicate/unique values,
|
||||
/// top10, aboveAverage and timePeriod. The x14 extension a main-section data bar links to by
|
||||
/// `x14:id` adds no rule, only that bar's solid fill (its other settings are skipped with a
|
||||
/// warning). Skipped with a warning (and so lost on save): other data bars, icon sets, colour
|
||||
/// scales and the text rules containsText, notContainsText, beginsWith and endsWith.
|
||||
pub(super) fn read_x14_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: &mut u64) {
|
||||
for cf in e.kids("conditionalFormatting") {
|
||||
let ranges = parse_sqref(cf.child("sqref").map(|s| s.text.as_str()));
|
||||
let block_cells = ranges.iter().map(RangeRef::count).fold(0u64, u64::saturating_add);
|
||||
for r in cf.kids("cfRule") {
|
||||
let ty = r.attr("type").unwrap_or("");
|
||||
let linked = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id.trim())).map(|(_, n)| *n);
|
||||
if let Some(n) = linked {
|
||||
match (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, with negatives in the bar's colour and no axis;
|
||||
// borders, lengths, other axis positions or negative colours are lost.
|
||||
let modelled = |k: &str, v: &str| {
|
||||
k == "gradient"
|
||||
|| (k == "axisPosition" && v == "none")
|
||||
|| (k == "negativeBarColorSameAsPositive" && matches!(v, "1" | "true"))
|
||||
};
|
||||
if db.attrs.iter().any(|(k, v)| !modelled(k, v)) || db.children.iter().any(|k| k.name != "cfvo") {
|
||||
cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was partly skipped (only its solid fill is kept)"));
|
||||
}
|
||||
}
|
||||
_ => cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
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"));
|
||||
break;
|
||||
if ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Only rule kinds whose formulas are kept and written back here; the others' x14
|
||||
// forms add settings (bar fills and axes, custom icons) the model doesn't hold.
|
||||
let supported = matches!(
|
||||
ty,
|
||||
"cellIs"
|
||||
| "expression"
|
||||
| "containsBlanks"
|
||||
| "notContainsBlanks"
|
||||
| "containsErrors"
|
||||
| "notContainsErrors"
|
||||
| "duplicateValues"
|
||||
| "uniqueValues"
|
||||
| "top10"
|
||||
| "aboveAverage"
|
||||
| "timePeriod"
|
||||
);
|
||||
if !supported {
|
||||
cx.warn(format!("Excel 2010 conditional format extension \"{ty}\" was skipped"));
|
||||
continue;
|
||||
}
|
||||
let style = Box::new(r.child("dxf").map(|x| crate::styles::read_x14_dxf(x, &cx.palette, &cx.num_fmts)).unwrap_or_default());
|
||||
let formulas: Vec<String> = r.kids("f").map(|f| from_file(f.text.trim())).collect();
|
||||
if let Some(rule) = cf_rule(cx, r, ty, formulas, style)
|
||||
&& !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
*kept_cells = total;
|
||||
if let Some(id) = ext_id {
|
||||
cx.cf_ext_ids.push((id, sheet.cond_formats.len()));
|
||||
}
|
||||
sheet.cond_formats.push(CondFormat {
|
||||
ranges: ranges.clone(),
|
||||
rule,
|
||||
priority: r.attr_u32("priority").unwrap_or(0),
|
||||
stop_if_true: r.flag("stopIfTrue", false),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,19 +11,23 @@ use gridcraft_model::{
|
||||
|
||||
use crate::drawing::{Obj, image_content_type, image_ext};
|
||||
use crate::fmla::text_to_file;
|
||||
use crate::styles::{color_attrs, dxf_id};
|
||||
use crate::styles::{color_attrs, dxf_id, dxf_xml};
|
||||
use crate::tables::{paper_id, px_to_col_width, px_to_pt};
|
||||
use crate::write::{
|
||||
CT_CHART, CT_COMMENTS, CT_DRAWING, CT_TABLE, CT_THREADED_COMMENTS, NS_MAIN, NS_REL, NS_THREADED, Out, REL_THREADED_COMMENT, Rels, XML_DECL,
|
||||
x14_cf_rule_guid,
|
||||
};
|
||||
use crate::xml::{encode_xstring, esc, esc_attr, num, push_a1, push_u64};
|
||||
|
||||
/// The worksheet extension holding Excel 2010 conditional formats.
|
||||
const EXT_X14_CF: &str = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}";
|
||||
|
||||
mod parts;
|
||||
mod rules;
|
||||
|
||||
pub(crate) use parts::password_attrs;
|
||||
use parts::{autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_name, table_xml, thread_ids, threaded_xml, vml_xml};
|
||||
use rules::{cf_rule_xml, solid_bar_id, validation_xml, x14_cfvo};
|
||||
use rules::{cf_rule_xml, solid_bar_x14, validation_xml, x14_cf_rule_xml};
|
||||
|
||||
fn sqref(ranges: &[RangeRef]) -> String {
|
||||
ranges.iter().map(|r| r.a1()).collect::<Vec<_>>().join(" ")
|
||||
@@ -193,7 +197,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
|
||||
write_sheet_data(&mut s, SheetCellData { workbook: wb, index: si, sheet, overrides: &overrides, extra: &extra, dynamic: &dynamic }, &sid, out);
|
||||
|
||||
let prio = write_sheet_rules(&mut s, sheet, &mut rels, out);
|
||||
let x14_cf = write_sheet_rules(&mut s, sheet, &mut rels, out);
|
||||
let kept = write_sheet_printing(&mut s, sheet, &mut rels, out);
|
||||
|
||||
write_sheet_drawing(&mut s, wb, si, sheet, &mut rels, out);
|
||||
@@ -214,7 +218,7 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
}
|
||||
let _ = write!(s, "<tableParts count=\"{}\">{parts}</tableParts>", tables.len());
|
||||
}
|
||||
write_sheet_extensions(&mut s, sheet, &prio);
|
||||
write_sheet_extensions(&mut s, sheet, &x14_cf);
|
||||
s.push_str("</worksheet>");
|
||||
(s, rels)
|
||||
}
|
||||
@@ -228,31 +232,13 @@ struct CellWriteInput<'a> {
|
||||
dynamic_range: Option<&'a RangeRef>,
|
||||
}
|
||||
|
||||
fn write_sheet_extensions(s: &mut String, sheet: &Sheet, prio: &[u32]) {
|
||||
// Excel 2010 extensions: solid data bars, then sparklines.
|
||||
let solid_bars: Vec<(&CondFormat, u32)> = sheet
|
||||
.cond_formats
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, cf)| !cf.ranges.is_empty() && matches!(cf.rule, CfRule::DataBar { gradient: false, .. }))
|
||||
.map(|(i, cf)| (cf, prio.get(i).copied().unwrap_or(1)))
|
||||
.collect();
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
fn write_sheet_extensions(s: &mut String, sheet: &Sheet, x14_cf: &str) {
|
||||
// Excel 2010 extensions: conditional formats, then sparklines.
|
||||
if !x14_cf.is_empty() || !sheet.sparklines.is_empty() {
|
||||
s.push_str("<extLst>");
|
||||
}
|
||||
if !solid_bars.is_empty() {
|
||||
let _ = write!(
|
||||
s,
|
||||
"<ext uri=\"{{78C0D931-6437-407d-A8A1-0F90B4350D7D}}\" xmlns:x14=\"{X14_NS}\" xmlns:xm=\"{XM_NS}\"><x14:conditionalFormattings>"
|
||||
);
|
||||
for (cf, p) in &solid_bars {
|
||||
if let CfRule::DataBar { min, max, .. } = &cf.rule {
|
||||
let (id, lo, hi) = (solid_bar_id(*p), x14_cfvo(min), x14_cfvo(max));
|
||||
let _ = write!(s, "<x14:conditionalFormatting><x14:cfRule type=\"dataBar\" id=\"{id}\"><x14:dataBar gradient=\"0\">{lo}{hi}");
|
||||
let _ = write!(s, "</x14:dataBar></x14:cfRule><xm:sqref>{}</xm:sqref></x14:conditionalFormatting>", sqref(&cf.ranges));
|
||||
}
|
||||
}
|
||||
s.push_str("</x14:conditionalFormattings></ext>");
|
||||
if !x14_cf.is_empty() {
|
||||
let _ = write!(s, "<ext uri=\"{EXT_X14_CF}\" xmlns:x14=\"{X14_NS}\"><x14:conditionalFormattings>{x14_cf}</x14:conditionalFormattings></ext>");
|
||||
}
|
||||
if !sheet.sparklines.is_empty() {
|
||||
let _ = write!(s, "<ext uri=\"{{05C60535-1F16-4fd2-B633-F4F36F0B64E0}}\" xmlns:x14=\"{X14_NS}\"><x14:sparklineGroups xmlns:xm=\"{XM_NS}\">");
|
||||
@@ -275,7 +261,7 @@ fn write_sheet_extensions(s: &mut String, sheet: &Sheet, prio: &[u32]) {
|
||||
}
|
||||
s.push_str("</x14:sparklineGroups></ext>");
|
||||
}
|
||||
if !solid_bars.is_empty() || !sheet.sparklines.is_empty() {
|
||||
if !x14_cf.is_empty() || !sheet.sparklines.is_empty() {
|
||||
s.push_str("</extLst>");
|
||||
}
|
||||
}
|
||||
@@ -470,7 +456,7 @@ fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, o
|
||||
kept
|
||||
}
|
||||
|
||||
fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> Vec<u32> {
|
||||
fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> String {
|
||||
// sheetProtection
|
||||
if let Some(p) = &sheet.protection {
|
||||
s.push_str("<sheetProtection sheet=\"1\" objects=\"1\" scenarios=\"1\"");
|
||||
@@ -524,16 +510,34 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O
|
||||
*p = rank as u32 + 1;
|
||||
}
|
||||
}
|
||||
// Cell-value and formula rules referring to another sheet go to the Excel 2010 extension.
|
||||
// Excel for Mac 16.114 also writes cross-sheet expression rules there (the tested synthetic
|
||||
// files opened without a repair prompt), using this URI. It stores cross-sheet cfvo rules for
|
||||
// colour scales, data bars and icon sets only in x14; GridCraft writes those in the main
|
||||
// section, and drops x14-only forms on read with a warning. GridCraft-written test files with
|
||||
// those main-section rules also opened without a repair prompt.
|
||||
// A solid data bar is in both sections: the extension holds its fill.
|
||||
let mut x14_cf = String::new();
|
||||
for (i, cf) in sheet.cond_formats.iter().enumerate() {
|
||||
if cf.ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let _ = write!(
|
||||
s,
|
||||
"<conditionalFormatting sqref=\"{}\">{}</conditionalFormatting>",
|
||||
sqref(&cf.ranges),
|
||||
cf_rule_xml(cf, prio.get(i).copied().unwrap_or(1), out)
|
||||
);
|
||||
let priority = prio.get(i).copied().unwrap_or(1);
|
||||
let x14 = match x14_cf_rule_xml(cf, &sheet.name, priority, out) {
|
||||
Some(rule) => Some(rule),
|
||||
None => {
|
||||
let _ =
|
||||
write!(s, "<conditionalFormatting sqref=\"{}\">{}</conditionalFormatting>", sqref(&cf.ranges), cf_rule_xml(cf, priority, out));
|
||||
solid_bar_x14(cf, priority)
|
||||
}
|
||||
};
|
||||
if let Some(rule) = x14 {
|
||||
let _ = write!(
|
||||
x14_cf,
|
||||
"<x14:conditionalFormatting xmlns:xm=\"{XM_NS}\">{rule}<xm:sqref>{}</xm:sqref></x14:conditionalFormatting>",
|
||||
sqref(&cf.ranges)
|
||||
);
|
||||
}
|
||||
}
|
||||
let vals: Vec<&Validation> = sheet.validations.iter().filter(|v| !v.ranges.is_empty()).collect();
|
||||
if !vals.is_empty() {
|
||||
@@ -578,7 +582,7 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O
|
||||
}
|
||||
s.push_str("</hyperlinks>");
|
||||
}
|
||||
prio
|
||||
x14_cf
|
||||
}
|
||||
|
||||
struct SheetCellData<'a> {
|
||||
|
||||
@@ -183,6 +183,60 @@ pub(super) fn cf_rule_xml(cf: &CondFormat, priority: u32, out: &mut Out) -> Stri
|
||||
}
|
||||
}
|
||||
|
||||
/// The x14 rule a solid data bar's `cfRule` links to (it holds the fill); `None` for other rules.
|
||||
/// GridCraft draws negative values in the bar's colour from the low end, with no axis; the x14
|
||||
/// defaults are an automatic axis and a separate negative colour, so both are written out.
|
||||
pub(super) fn solid_bar_x14(cf: &CondFormat, priority: u32) -> Option<String> {
|
||||
let CfRule::DataBar { min, max, gradient: false, .. } = &cf.rule else { return None };
|
||||
let (id, lo, hi) = (solid_bar_id(priority), x14_cfvo(min), x14_cfvo(max));
|
||||
Some(format!(
|
||||
"<x14:cfRule type=\"dataBar\" id=\"{id}\"><x14:dataBar gradient=\"0\" negativeBarColorSameAsPositive=\"1\" axisPosition=\"none\">{lo}{hi}</x14:dataBar></x14:cfRule>"
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether formula `f` refers to a sheet other than `own`, and whether it refers to a 3-D span of
|
||||
/// sheets.
|
||||
fn sheet_refs(f: &str, own: &str) -> (bool, bool) {
|
||||
let Ok(e) = gridcraft_formula::parse(f.trim_start_matches('=')) else { return (false, false) };
|
||||
let refs = e.references();
|
||||
let other = refs.iter().any(|r| match &r.sheet {
|
||||
gridcraft_formula::SheetSel::Named(n) => !n.chars().flat_map(char::to_lowercase).eq(own.chars().flat_map(char::to_lowercase)),
|
||||
_ => false,
|
||||
});
|
||||
let span = refs.iter().any(|r| matches!(r.sheet, gridcraft_formula::SheetSel::Span(..)));
|
||||
(other, span)
|
||||
}
|
||||
|
||||
/// The Excel 2010 form (`x14:cfRule`, `xm:f` formulas, inline `x14:dxf`) of a cell-value or
|
||||
/// formula rule that refers to another sheet; `None` for rules that belong in the main section.
|
||||
/// MS-XLSX 2.6.27 (CT_CfRule) forbids 3-D spans (`sheet-range-reference`) in `xm:f`, so a rule
|
||||
/// with one stays in the main section.
|
||||
pub(super) fn x14_cf_rule_xml(cf: &CondFormat, own: &str, priority: u32, out: &mut Out) -> Option<String> {
|
||||
let (ty, extra, formulas, style): (&str, String, Vec<&str>, &Style) = match &cf.rule {
|
||||
CfRule::CellIs { op, a, b, style } => {
|
||||
("cellIs", format!(" operator=\"{}\"", cf_op_name(*op)), std::iter::once(a.as_str()).chain(b.as_deref()).collect(), style)
|
||||
}
|
||||
CfRule::Expression { formula, style } => ("expression", String::new(), vec![formula.as_str()], style),
|
||||
_ => return None,
|
||||
};
|
||||
let refs: Vec<(bool, bool)> = formulas.iter().map(|f| sheet_refs(f, own)).collect();
|
||||
if !refs.iter().any(|&(other, _)| other) || refs.iter().any(|&(_, span)| span) {
|
||||
return None;
|
||||
}
|
||||
out.x14_cf_rules += 1;
|
||||
let mut s = format!(
|
||||
"<x14:cfRule type=\"{ty}\" priority=\"{priority}\"{}{extra} id=\"{}\">",
|
||||
if cf.stop_if_true { " stopIfTrue=\"1\"" } else { "" },
|
||||
x14_cf_rule_guid(out.x14_cf_rules)
|
||||
);
|
||||
for f in formulas {
|
||||
let _ = write!(s, "<xm:f>{}</xm:f>", esc(&text_to_file(f)));
|
||||
}
|
||||
s.push_str(&dxf_xml("x14:dxf", style, &mut out.num_fmts));
|
||||
s.push_str("</x14:cfRule>");
|
||||
Some(s)
|
||||
}
|
||||
|
||||
fn validation_formula(f: &str) -> String {
|
||||
let f = f.trim();
|
||||
if f.starts_with('"') {
|
||||
|
||||
+61
-46
@@ -444,6 +444,14 @@ fn read_dxf<'a>(x: &'a El, palette: &[u32], fmts: &HashMap<u32, NumFmt>, inline_
|
||||
s
|
||||
}
|
||||
|
||||
/// An inline Excel 2010 `x14:dxf` differential format, resolving `numFmtId` against `cx.num_fmts`.
|
||||
pub fn read_x14_dxf(x: &El, palette: &[u32], fmts: &HashMap<u32, String>) -> Style {
|
||||
let shared: HashMap<u32, NumFmt> =
|
||||
x.child("numFmt").and_then(|n| n.attr_u32("numFmtId")).and_then(|id| fmts.get(&id).map(|c| (id, NumFmt::new(c)))).into_iter().collect();
|
||||
let mut inline_fmts = HashMap::new();
|
||||
read_dxf(x, palette, &shared, &mut inline_fmts)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- writing
|
||||
|
||||
pub fn color_attrs(c: &Color) -> String {
|
||||
@@ -639,14 +647,16 @@ fn intern<T: Clone + Eq + std::hash::Hash>(list: &mut Vec<T>, map: &mut HashMap<
|
||||
i
|
||||
}
|
||||
|
||||
/// Number format ids assigned while writing.
|
||||
struct NumFmts {
|
||||
/// Number format ids assigned while writing. Worksheets that carry inline differential formats
|
||||
/// (`x14:dxf`) assign ids first, through [`crate::write::Out`]; `styles.xml` lists them all.
|
||||
#[derive(Default)]
|
||||
pub struct NumFmts {
|
||||
custom: Vec<(u32, String)>,
|
||||
map: HashMap<String, u32>,
|
||||
}
|
||||
|
||||
impl NumFmts {
|
||||
fn id(&mut self, code: &str) -> u32 {
|
||||
pub fn id(&mut self, code: &str) -> u32 {
|
||||
if let Some(id) = builtin_id(code) {
|
||||
return id;
|
||||
}
|
||||
@@ -662,10 +672,10 @@ impl NumFmts {
|
||||
|
||||
/// `styles.xml` for the workbook: one cell format per model style, in `StyleId` order (so a
|
||||
/// cell's `s` attribute is its style id), plus the given differential formats.
|
||||
/// `extra_fmts` are number formats used outside cell styles (PivotTable value fields); the
|
||||
/// returned map gives the id of every custom format written.
|
||||
pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (String, HashMap<String, u32>) {
|
||||
let mut nf = NumFmts { custom: vec![], map: HashMap::new() };
|
||||
/// `extra_fmts` are number formats used outside cell styles (PivotTable value fields); `nf`
|
||||
/// holds the ids worksheets already assigned. The returned map gives the id of every custom
|
||||
/// format written.
|
||||
pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String], mut nf: NumFmts) -> (String, HashMap<String, u32>) {
|
||||
let mut fonts: Vec<Font> = vec![];
|
||||
let mut font_map = HashMap::new();
|
||||
let mut fills: Vec<Fill> = vec![Fill::default(), Fill { pattern: PatternType::Gray125, fg: Color::Auto, bg: Color::Auto }];
|
||||
@@ -745,44 +755,7 @@ pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (St
|
||||
|
||||
let mut dx = String::new();
|
||||
for d in dxfs {
|
||||
dx.push_str("<dxf>");
|
||||
let def = Style::default();
|
||||
let st = &d.dxf_stated;
|
||||
if d.font.bold
|
||||
|| d.font.italic
|
||||
|| d.font.strike
|
||||
|| d.font.underline != Underline::None
|
||||
|| d.font.color != Color::Auto
|
||||
|| d.font.vert != VertAlign::Baseline
|
||||
|| d.font.size != def.font.size
|
||||
|| d.font.name != def.font.name
|
||||
|| st.bold
|
||||
|| st.italic
|
||||
|| st.strike
|
||||
|| st.underline
|
||||
|| st.size
|
||||
|| st.name
|
||||
|| st.scheme.is_some()
|
||||
{
|
||||
dx.push_str(&font_xml(&d.font, Some(st), false));
|
||||
}
|
||||
if d.num_fmt != def.num_fmt {
|
||||
let id = nf.id(d.num_fmt.as_str());
|
||||
let _ = write!(dx, "<numFmt numFmtId=\"{id}\" formatCode=\"{}\"/>", esc_attr(d.num_fmt.as_str()));
|
||||
}
|
||||
if d.fill != def.fill {
|
||||
dx.push_str(&fill_xml(&d.fill, true));
|
||||
}
|
||||
if let Some(a) = alignment_xml(&d.align) {
|
||||
dx.push_str(&a);
|
||||
}
|
||||
if d.borders != def.borders {
|
||||
dx.push_str(&border_xml(&d.borders));
|
||||
}
|
||||
if st.protection || d.protection != def.protection {
|
||||
let _ = write!(dx, "<protection locked=\"{}\" hidden=\"{}\"/>", d.protection.locked as u8, d.protection.hidden as u8);
|
||||
}
|
||||
dx.push_str("</dxf>");
|
||||
dx.push_str(&dxf_xml("dxf", d, &mut nf));
|
||||
}
|
||||
for f in extra_fmts {
|
||||
nf.id(f);
|
||||
@@ -820,6 +793,48 @@ pub fn write_styles(wb: &Workbook, dxfs: &[Style], extra_fmts: &[String]) -> (St
|
||||
(s, nf.map)
|
||||
}
|
||||
|
||||
/// A differential format element named `tag` (`dxf`, or `x14:dxf` inline in a worksheet rule).
|
||||
pub fn dxf_xml(tag: &str, d: &Style, nf: &mut NumFmts) -> String {
|
||||
let mut dx = format!("<{tag}>");
|
||||
let def = Style::default();
|
||||
if d.font.bold
|
||||
|| d.font.italic
|
||||
|| d.font.strike
|
||||
|| d.font.underline != Underline::None
|
||||
|| d.font.color != Color::Auto
|
||||
|| d.font.vert != VertAlign::Baseline
|
||||
|| d.font.size != def.font.size
|
||||
|| d.font.name != def.font.name
|
||||
|| d.dxf_stated.bold
|
||||
|| d.dxf_stated.italic
|
||||
|| d.dxf_stated.strike
|
||||
|| d.dxf_stated.underline
|
||||
|| d.dxf_stated.size
|
||||
|| d.dxf_stated.name
|
||||
|| d.dxf_stated.scheme.is_some()
|
||||
{
|
||||
dx.push_str(&font_xml(&d.font, Some(&d.dxf_stated), false));
|
||||
}
|
||||
if d.num_fmt != def.num_fmt {
|
||||
let id = nf.id(d.num_fmt.as_str());
|
||||
let _ = write!(dx, "<numFmt numFmtId=\"{id}\" formatCode=\"{}\"/>", esc_attr(d.num_fmt.as_str()));
|
||||
}
|
||||
if d.fill != def.fill {
|
||||
dx.push_str(&fill_xml(&d.fill, true));
|
||||
}
|
||||
if let Some(a) = alignment_xml(&d.align) {
|
||||
dx.push_str(&a);
|
||||
}
|
||||
if d.borders != def.borders {
|
||||
dx.push_str(&border_xml(&d.borders));
|
||||
}
|
||||
if d.dxf_stated.protection || d.protection != def.protection {
|
||||
let _ = write!(dx, "<protection locked=\"{}\" hidden=\"{}\"/>", d.protection.locked as u8, d.protection.hidden as u8);
|
||||
}
|
||||
let _ = write!(dx, "</{tag}>");
|
||||
dx
|
||||
}
|
||||
|
||||
/// Index of a differential format, adding it when new.
|
||||
pub fn dxf_id(dxfs: &mut Vec<Style>, s: &Style) -> u32 {
|
||||
if let Some(i) = dxfs.iter().position(|d| d == s) {
|
||||
@@ -856,7 +871,7 @@ mod tests {
|
||||
let mut wb = Workbook::new();
|
||||
wb.styles.intern(styles.xfs[1].clone());
|
||||
wb.cell_styles = styles.named.clone();
|
||||
let (xml, _) = write_styles(&wb, &styles.dxfs, &[]);
|
||||
let (xml, _) = write_styles(&wb, &styles.dxfs, &[], NumFmts::default());
|
||||
let root = crate::xml::parse(xml.as_bytes()).unwrap();
|
||||
for section in ["dxfs", "cellXfs", "cellStyleXfs"] {
|
||||
let orders: Vec<_> = root
|
||||
|
||||
@@ -20,6 +20,7 @@ fn equation(id: u32, cell: &str, latex: &str, ink: Color) -> Shape {
|
||||
text: latex.into(),
|
||||
format: Default::default(),
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +162,7 @@ fn a_text_box_stays_a_text_box_and_hostile_sources_survive() {
|
||||
text: "plain".into(),
|
||||
format: Default::default(),
|
||||
math: Default::default(),
|
||||
rotation: 0.0,
|
||||
});
|
||||
wb.sheets[0] = Arc::new(sh);
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
@@ -210,7 +212,7 @@ fn a_marker_over_garbage_office_math_falls_back_without_panicking() {
|
||||
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
|
||||
let mut d = drawing(&parts);
|
||||
let (m0, m1) = (d.find("<m:oMath>").unwrap(), d.find("</m:oMath>").unwrap());
|
||||
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:sPre/><m:f><m:num/></m:f><m:r/><m:t>junk</m:t><m:oMath/><m:e/></m:oMath>");
|
||||
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:unknown/><m:r/><m:t>junk</m:t><m:oMath/><m:e/></m:oMath>");
|
||||
parts.insert(name.clone(), d.into_bytes());
|
||||
let (back, _) = read_xlsx(&rezip(&parts)).unwrap();
|
||||
let s = shapes(&back);
|
||||
@@ -233,17 +235,14 @@ fn office_math_outside_the_subset_reads_the_fallback() {
|
||||
let mut parts = unzip(&write_xlsx(&wb).unwrap());
|
||||
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
|
||||
let mut d = drawing(&parts);
|
||||
// Another writer: no GridCraft source, Office Math the reader does not convert (a
|
||||
// pre-subscript), and a fallback text box with its own text.
|
||||
// Another writer: no GridCraft source, Office Math the reader does not convert,
|
||||
// and a fallback text box with its own text.
|
||||
while let Some(a) = d.find(" descr=\"gridcraft:latex:") {
|
||||
let b = d[a + 8..].find('"').unwrap() + a + 9;
|
||||
d.replace_range(a..b, "");
|
||||
}
|
||||
let (m0, m1) = (d.find("<m:oMath>").unwrap(), d.find("</m:oMath>").unwrap());
|
||||
d.replace_range(
|
||||
m0..m1 + "</m:oMath>".len(),
|
||||
"<m:oMath><m:sPre><m:sub><m:r><m:t>1</m:t></m:r></m:sub><m:sup><m:r><m:t>2</m:t></m:r></m:sup><m:e><m:r><m:t>y</m:t></m:r></m:e></m:sPre></m:oMath>",
|
||||
);
|
||||
d.replace_range(m0..m1 + "</m:oMath>".len(), "<m:oMath><m:unknown><m:e><m:r><m:t>y</m:t></m:r></m:e></m:unknown></m:oMath>");
|
||||
let fb = d.find("<mc:Fallback>").unwrap();
|
||||
let t = d[fb..].find("<a:t>x^2</a:t>").unwrap() + fb;
|
||||
d.replace_range(t..t + "<a:t>x^2</a:t>".len(), "<a:t>the writer's fallback</a:t>");
|
||||
@@ -484,3 +483,44 @@ fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() {
|
||||
// The Office Math box keeps the size of the equation.
|
||||
assert!(!d.contains("<a:endParaRPr lang=\"en-US\" sz=\"1100\"/>"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_office_math_without_a_saved_source_keeps_visible_text() {
|
||||
let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]);
|
||||
let original = unzip(&write_xlsx(&wb).unwrap());
|
||||
let name = original.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
|
||||
let d = drawing(&original);
|
||||
let c0 = d.find("<mc:Choice").unwrap();
|
||||
let c1 = d.find("</mc:Choice>").unwrap();
|
||||
let choice = &d[c0..c1];
|
||||
let mut sp = choice[choice.find("<xdr:sp ").unwrap()..].to_string();
|
||||
while let Some(a) = sp.find(" descr=\"gridcraft:latex:") {
|
||||
let b = sp[a + 8..].find('"').unwrap() + a + 9;
|
||||
sp.replace_range(a..b, "");
|
||||
}
|
||||
let a0 = d.find("<mc:AlternateContent").unwrap();
|
||||
let a1 = d.find("</mc:AlternateContent>").unwrap() + "</mc:AlternateContent>".len();
|
||||
for (body, expected) in [
|
||||
("<a:p><a14:m><m:oMath><m:r><m:t>x^2</m:t></m:r></m:oMath></a14:m></a:p>", "x^2"),
|
||||
(
|
||||
"<a:p><a:r><a:t>Solve: </a:t></a:r><a14:m><m:oMath><m:r><m:t>x^2</m:t></m:r></m:oMath></a14:m><a:r><a:t> please</a:t></a:r></a:p><a:p><a:r><a:t>next</a:t></a:r></a:p>",
|
||||
"Solve: x^2 please\nnext",
|
||||
),
|
||||
("<a:p><a14:m><m:oMath><m:unknown><m:r><m:t>λ^2</m:t></m:r></m:unknown></m:oMath></a14:m></a:p>", "λ^2"),
|
||||
] {
|
||||
let mut shape = sp.clone();
|
||||
let start = shape.find("<xdr:txBody>").unwrap();
|
||||
let end = shape.find("</xdr:txBody>").unwrap() + "</xdr:txBody>".len();
|
||||
shape.replace_range(start..end, &format!("<xdr:txBody>{body}</xdr:txBody>"));
|
||||
let mut xml = d.clone();
|
||||
xml.replace_range(a0..a1, &shape);
|
||||
let mut parts = original.clone();
|
||||
parts.insert(name.clone(), xml.into_bytes());
|
||||
let back = shapes(&read_xlsx(&rezip(&parts)).unwrap().0);
|
||||
assert_eq!(back.len(), 1);
|
||||
assert_ne!(back[0].kind, ShapeKind::Equation);
|
||||
assert_eq!(back[0].text, expected);
|
||||
let again = shapes(&read_xlsx(&write_xlsx(&book(back)).unwrap()).unwrap().0);
|
||||
assert_eq!(again[0].text, expected);
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,7 @@ fn exported_ink_has_a_visible_unfilled_path_and_correct_stroke() {
|
||||
line: Color::Rgb(0xA12BCD),
|
||||
text: "-10.0,5.0;50.0,40.0;90.0,10.0".into(),
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -111,6 +111,19 @@ fn ods_repeats_merges_sheet_names_and_empty_tail_remain_sparse() {
|
||||
assert_eq!(wb.sheets[1].value(CellRef::new(0, 0)), text("second sheet"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_tables_are_the_only_sheets_with_unique_valid_names() {
|
||||
let cell = r#"<table:table-row><table:table-cell office:value-type="float" office:value="1"/></table:table-row>"#;
|
||||
let bytes = ods(&format!(
|
||||
r#"<table:table table:name="Data">{cell}</table:table><table:table table:name="data">{cell}</table:table><table:table table:name="a/b">{cell}</table:table>"#
|
||||
));
|
||||
let (wb, report) = read_ods(&bytes).unwrap();
|
||||
let names: Vec<&str> = wb.sheets.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Data", "data (2)", "ab"]);
|
||||
assert!(wb.sheets.iter().all(|s| s.value(CellRef::new(0, 0)) == Value::Number(1.0)));
|
||||
assert!(report.warnings.iter().any(|w| w.contains("renamed")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ods_dates_and_durations_use_formats_and_unsupported_values_stay_text() {
|
||||
let bytes = row(r#"
|
||||
@@ -158,8 +171,8 @@ fn ods_rejects_bad_packages_encryption_and_truncated_xml() {
|
||||
for mime in [b"application/zip".as_slice(), b"application/vnd.oasis.opendocument.spreadsheet "] {
|
||||
assert!(read_ods(&make_zip(&[("mimetype", mime), ("content.xml", xml.as_bytes())])).is_err());
|
||||
}
|
||||
let encrypted =
|
||||
br#"<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:encryption-data/></manifest:manifest>"#;
|
||||
// As LibreOffice writes it: the encryption data belongs to the encrypted file's entry.
|
||||
let encrypted = br#"<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"><manifest:encryption-data manifest:checksum-type="SHA1/1K" manifest:checksum="AAAA"/></manifest:file-entry></manifest:manifest>"#;
|
||||
assert!(
|
||||
read_ods(&make_zip(&[("mimetype", MIME), ("META-INF/manifest.xml", encrypted), ("content.xml", xml.as_bytes())]))
|
||||
.unwrap_err()
|
||||
|
||||
@@ -369,6 +369,7 @@ fn sample() -> Workbook {
|
||||
line: Color::Rgb(0x000000),
|
||||
text: "Hi\nthere".into(),
|
||||
format: Default::default(),
|
||||
rotation: 30.0,
|
||||
});
|
||||
s.shapes.push(Shape {
|
||||
math: Default::default(),
|
||||
@@ -379,6 +380,7 @@ fn sample() -> Workbook {
|
||||
line: Color::Rgb(0xFF0000),
|
||||
text: String::new(),
|
||||
format: Default::default(),
|
||||
rotation: 0.0,
|
||||
});
|
||||
s.shapes.push(Shape {
|
||||
math: Default::default(),
|
||||
@@ -401,6 +403,7 @@ fn sample() -> Workbook {
|
||||
anchor: Some(ShapeTextAnchor::Bottom),
|
||||
rtl: true,
|
||||
},
|
||||
rotation: 0.0,
|
||||
});
|
||||
let base_chart = Chart {
|
||||
id: 20,
|
||||
@@ -1014,6 +1017,139 @@ fn icon_sets_always_write_one_cfvo_per_icon() {
|
||||
assert_eq!(rules, [3, 4, 5]);
|
||||
}
|
||||
|
||||
const X14_CF_SHEET: &str = r#"<sheetData/>
|
||||
<conditionalFormatting sqref="B1:B5"><cfRule type="dataBar" priority="2"><dataBar><cfvo type="min"/><cfvo type="max"/><color rgb="FF638EC6"/></dataBar><extLst><ext uri="{B025F937-C7B1-47D3-B67F-A62EFF666E3E}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"><x14:id>{00000000-0000-0000-0000-00000000000A}</x14:id></ext></extLst></cfRule></conditionalFormatting>
|
||||
<extLst><ext uri="{78C0D931-6437-407d-A8EE-F0AAD7539E65}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"><x14:conditionalFormattings>
|
||||
<x14:conditionalFormatting xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">
|
||||
<x14:cfRule type="cellIs" priority="3" operator="between" id="{00000000-0000-0000-0000-000000000001}"><xm:f>Lists!$A$1</xm:f><xm:f>Lists!$A$2</xm:f><x14:dxf><font><b/><color rgb="FF4F5051"/></font><numFmt numFmtId="170" formatCode="0.0%"/><fill><patternFill><bgColor rgb="FFFFC7CE"/></patternFill></fill><border><left style="thin"><color rgb="FF000000"/></left></border></x14:dxf></x14:cfRule>
|
||||
<x14:cfRule type="expression" priority="1" stopIfTrue="1" id="{00000000-0000-0000-0000-000000000002}"><xm:f>A1=Lists!$B$1</xm:f><x14:dxf><fill><patternFill><bgColor rgb="FFFFEB9C"/></patternFill></fill></x14:dxf></x14:cfRule>
|
||||
<xm:sqref>A1:A10 C1</xm:sqref></x14:conditionalFormatting>
|
||||
<x14:conditionalFormatting xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><x14:cfRule type="dataBar" id="{00000000-0000-0000-0000-00000000000A}"><x14:dataBar minLength="0" maxLength="100" gradient="0"><x14:cfvo type="autoMin"/><x14:cfvo type="autoMax"/></x14:dataBar></x14:cfRule><xm:sqref>B1:B5</xm:sqref></x14:conditionalFormatting>
|
||||
<x14:conditionalFormatting xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><x14:cfRule type="iconSet" priority="4" id="{00000000-0000-0000-0000-000000000003}"><x14:iconSet iconSet="3Stars"><x14:cfvo type="percent"><xm:f>0</xm:f></x14:cfvo><x14:cfvo type="percent"><xm:f>33</xm:f></x14:cfvo><x14:cfvo type="percent"><xm:f>67</xm:f></x14:cfvo></x14:iconSet></x14:cfRule><xm:sqref>D1:D3</xm:sqref></x14:conditionalFormatting>
|
||||
</x14:conditionalFormattings></ext></extLst>"#;
|
||||
|
||||
/// Rules in the `x14:conditionalFormattings` extension (such as those referring to other sheets)
|
||||
/// carry `xm:f` formulas and an inline `x14:dxf`; their priorities interleave with the main
|
||||
/// section's. A data bar's linked extension adds no rule, only the bar's solid fill (its other
|
||||
/// settings are skipped with a warning); x14 icon sets are skipped with a warning.
|
||||
#[test]
|
||||
fn x14_conditional_formats_are_read() {
|
||||
let (wb, rep) = read_xlsx(&super::minimal(X14_CF_SHEET, &[], "", "")).unwrap();
|
||||
let mut cfs = wb.sheet(0).unwrap().cond_formats.clone();
|
||||
cfs.sort_by_key(|cf| cf.priority);
|
||||
assert_eq!(cfs.iter().map(|cf| cf.priority).collect::<Vec<_>>(), [1, 2, 3], "{cfs:?}");
|
||||
let [expr, bar, cell] = &cfs[..] else { panic!("{cfs:?}") };
|
||||
assert_eq!(expr.ranges, [rr("A1:A10"), rr("C1")]);
|
||||
assert!(expr.stop_if_true);
|
||||
match &expr.rule {
|
||||
CfRule::Expression { formula, style } => {
|
||||
assert_eq!(formula, "A1=Lists!$B$1");
|
||||
assert_eq!(style.fill, Fill::solid(Color::Rgb(0xFFEB9C)));
|
||||
}
|
||||
r => panic!("{r:?}"),
|
||||
}
|
||||
assert!(matches!(bar.rule, CfRule::DataBar { gradient: false, .. }), "{bar:?}");
|
||||
assert_eq!(bar.ranges, [rr("B1:B5")]);
|
||||
match &cell.rule {
|
||||
CfRule::CellIs { op, a, b, style } => {
|
||||
assert_eq!((*op, a.as_str(), b.as_deref()), (CfOperator::Between, "Lists!$A$1", Some("Lists!$A$2")));
|
||||
assert!(style.font.bold);
|
||||
assert_eq!(style.font.color, Color::Rgb(0x4F5051));
|
||||
assert_eq!(style.num_fmt.as_str(), "0.0%");
|
||||
assert_eq!(style.fill, Fill::solid(Color::Rgb(0xFFC7CE)));
|
||||
assert_eq!(style.borders.left.style, BorderStyle::Thin);
|
||||
}
|
||||
r => panic!("{r:?}"),
|
||||
}
|
||||
// Unsupported x14 kinds still warn, by name; nothing else does.
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("\"dataBar\"")), "{:?}", rep.warnings);
|
||||
assert!(rep.warnings.iter().any(|w| w.contains("\"iconSet\"")), "{:?}", rep.warnings);
|
||||
assert_eq!(rep.warnings.iter().filter(|w| w.contains("conditional format")).count(), 2, "{:?}", rep.warnings);
|
||||
}
|
||||
|
||||
/// A rule referring to another sheet is written in the x14 extension (as the LibreOffice-saved
|
||||
/// file that motivated this places it), ahead of the sparklines in the one `extLst`; other rules
|
||||
/// stay in the main section, and so does a rule with a 3-D span, which MS-XLSX 2.6.27 forbids in
|
||||
/// `xm:f`.
|
||||
#[test]
|
||||
fn cross_sheet_rules_are_written_in_the_x14_extension() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.push(Arc::new(Sheet::new("Vehicle Range")));
|
||||
let grey = Style { font: Font { color: Color::Rgb(0x4F5051), ..Style::default().font }, num_fmt: NumFmt::new("0.0%"), ..Style::default() };
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
let rules = [
|
||||
(CfRule::Expression { formula: "E1>Sheet1!$B$1".into(), style: Box::new(grey.clone()) }, false),
|
||||
(CfRule::CellIs { op: CfOperator::Equal, a: "'Vehicle Range'!$A$8".into(), b: None, style: Box::new(grey.clone()) }, true),
|
||||
(CfRule::CellIs { op: CfOperator::Greater, a: "5".into(), b: None, style: Box::new(grey.clone()) }, false),
|
||||
(CfRule::Expression { formula: "SUM('Sheet1:Vehicle Range'!$A$1)>0".into(), style: Box::new(grey) }, false),
|
||||
];
|
||||
for (i, (rule, stop_if_true)) in rules.into_iter().enumerate() {
|
||||
s.cond_formats.push(CondFormat { ranges: vec![rr("E1:E20")], rule, priority: i as u32 + 1, stop_if_true });
|
||||
}
|
||||
s.sparklines.push(Sparkline { cell: at("J2"), source: "B2:B3".into(), kind: SparklineKind::Line, color: Color::Auto, markers: false });
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
let (main, ext) = xml.split_once("<extLst>").unwrap();
|
||||
assert_eq!(main.matches("<cfRule ").count(), 3, "{main}");
|
||||
assert!(!main.contains("$A$8"), "{main}");
|
||||
assert!(main.contains("<formula>E1>Sheet1!$B$1</formula>"), "{main}");
|
||||
assert!(main.contains("<formula>SUM('Sheet1:Vehicle Range'!$A$1)>0</formula>"), "{main}");
|
||||
assert_eq!(ext.matches("<x14:cfRule ").count(), 1, "{ext}");
|
||||
assert_eq!(ext.matches("<extLst>").count(), 0, "one extLst: {ext}");
|
||||
let cf = ext.find("{78C0D931-6437-407d-A8EE-F0AAD7539E65}").unwrap();
|
||||
assert!(cf < ext.find("{05C60535-1F16-4fd2-B633-F4F36F0B64E0}").unwrap(), "conditional formats before sparklines: {ext}");
|
||||
assert!(ext.contains("xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\""), "{ext}");
|
||||
assert!(ext.contains("<x14:conditionalFormatting xmlns:xm=\"http://schemas.microsoft.com/office/excel/2006/main\">"), "{ext}");
|
||||
assert!(ext.contains("<x14:cfRule type=\"cellIs\" priority=\"2\" stopIfTrue=\"1\" operator=\"equal\" id=\"{"), "{ext}");
|
||||
assert!(ext.contains("<xm:f>'Vehicle Range'!$A$8</xm:f><x14:dxf><font><color rgb=\"FF4F5051\"/></font><numFmt numFmtId=\""), "{ext}");
|
||||
assert!(ext.contains("</x14:dxf></x14:cfRule><xm:sqref>E1:E20</xm:sqref></x14:conditionalFormatting>"), "{ext}");
|
||||
// The inline number format's id is the one `styles.xml` declares for its code.
|
||||
let id = ext.split("<numFmt numFmtId=\"").nth(1).and_then(|r| r.split('"').next()).unwrap();
|
||||
let mut styles = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("xl/styles.xml").unwrap().read_to_string(&mut styles).unwrap();
|
||||
assert!(styles.contains(&format!("<numFmt numFmtId=\"{id}\" formatCode=\"0.0%\"/>")), "{styles}");
|
||||
|
||||
let (back, rep) = read_xlsx(&bytes).unwrap();
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let mut got = back.sheet(0).unwrap().cond_formats.clone();
|
||||
got.sort_by_key(|cf| cf.priority);
|
||||
assert_eq!(got, wb.sheet(0).unwrap().cond_formats);
|
||||
}
|
||||
|
||||
/// A differential format's protection is written after its alignment and border (the CT_Dxf
|
||||
/// order: font, numFmt, fill, alignment, border, protection), both inline in an `x14:dxf` and in `styles.xml`, and reads back.
|
||||
#[test]
|
||||
fn dxf_protection_is_written_in_schema_order() {
|
||||
let mut wb = Workbook::new();
|
||||
wb.sheets.push(Arc::new(Sheet::new("Other")));
|
||||
let mut st = Style { fill: Fill::solid(Color::Rgb(0xFFC7CE)), ..Style::default() };
|
||||
st.align.h = HAlign::Center;
|
||||
st.protection = gridcraft_model::style::Protection { locked: false, hidden: true };
|
||||
st.borders.left.style = BorderStyle::Thin;
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
let rules = [
|
||||
CfRule::Expression { formula: "A1=Other!$A$1".into(), style: Box::new(st.clone()) },
|
||||
CfRule::Expression { formula: "A1>5".into(), style: Box::new(st) },
|
||||
];
|
||||
for (i, rule) in rules.into_iter().enumerate() {
|
||||
s.cond_formats.push(CondFormat { ranges: vec![rr("A1:A5")], rule, priority: i as u32 + 1, stop_if_true: false });
|
||||
}
|
||||
let bytes = write_xlsx(&wb).unwrap();
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
let mut styles = String::new();
|
||||
zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("xl/styles.xml").unwrap().read_to_string(&mut styles).unwrap();
|
||||
let dxfs = &styles[styles.find("<dxfs").unwrap()..];
|
||||
for part in [xml.as_str(), dxfs] {
|
||||
let p = part.find("<protection locked=\"0\" hidden=\"1\"/>").unwrap_or_else(|| panic!("{part}"));
|
||||
assert!(part.find("<alignment").unwrap() < part.find("<border>").unwrap() && part.find("<border>").unwrap() < p, "{part}");
|
||||
}
|
||||
let (back, rep) = read_xlsx(&bytes).unwrap();
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let mut got = back.sheet(0).unwrap().cond_formats.clone();
|
||||
got.sort_by_key(|cf| cf.priority);
|
||||
assert_eq!(got, wb.sheet(0).unwrap().cond_formats);
|
||||
}
|
||||
|
||||
/// Files have no `@` operator. An `@` that legacy Excel implies is written without it in a
|
||||
/// legacy formula (no dynamic-array metadata); any other `@x` is written as `_xlfn.SINGLE(x)`
|
||||
/// in a dynamic-array formula. Both read back as written in the model.
|
||||
@@ -1698,6 +1834,11 @@ fn solid_data_bar_survives_with_sparklines_and_gradient_neighbours() {
|
||||
// x14 cfvo values are `xm:f` children; a `val` attribute there is not valid x14.
|
||||
let (xml, _) = sheet1_xml(&bytes);
|
||||
assert!(xml.contains("<x14:cfvo type=\"num\"><xm:f>9</xm:f></x14:cfvo>"), "{xml}");
|
||||
// Both solid bars sit in the one x14 conditional format extension, under its MS-XLSX uri.
|
||||
assert_eq!(xml.matches("<ext uri=\"{78C0D931-6437-407d-A8EE-F0AAD7539E65}\"").count(), 1, "{xml}");
|
||||
assert_eq!(xml.matches("<x14:cfRule type=\"dataBar\"").count(), 2, "{xml}");
|
||||
// As drawn here: negatives in the bar's colour, no axis (Excel's x14 defaults differ), and read back without a warning.
|
||||
assert_eq!(xml.matches("<x14:dataBar gradient=\"0\" negativeBarColorSameAsPositive=\"1\" axisPosition=\"none\">").count(), 2, "{xml}");
|
||||
let (back, rep) = read_xlsx(&bytes).unwrap();
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let b = &back.sheets[0];
|
||||
|
||||
@@ -45,6 +45,7 @@ fn text_box(text: &str, format: ShapeFormat) -> Workbook {
|
||||
line: Color::Auto,
|
||||
text: text.into(),
|
||||
format,
|
||||
rotation: 0.0,
|
||||
math: Default::default(),
|
||||
});
|
||||
Workbook { sheets: vec![Arc::new(sheet)], ..Default::default() }
|
||||
@@ -86,6 +87,14 @@ fn shape_text_without_rtl_writes_unchanged_ppr() {
|
||||
assert!(!xml.contains("<a:pPr"), "no paragraph properties without alignment or direction: {xml}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotation_that_is_not_a_finite_number_reads_as_zero() {
|
||||
for rot in ["NaN", "inf", "-inf"] {
|
||||
let wb = read_drawing(&ARABIC_TEXT_BOX.replace("<a:xfrm>", &format!("<a:xfrm rot=\"{rot}\">")));
|
||||
assert_eq!(wb.sheet(0).unwrap().shapes[0].rotation, 0.0, "rot={rot}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_art_keeps_right_to_left_paragraphs() {
|
||||
let mut wb = text_box("مرحبا\nبالعالم", ShapeFormat { rtl: true, align: Some(ShapeTextAlign::Right), ..Default::default() });
|
||||
|
||||
@@ -111,6 +111,10 @@ pub struct Out {
|
||||
overrides: Vec<(String, String)>,
|
||||
defaults: BTreeMap<String, String>,
|
||||
pub dxfs: Vec<Style>,
|
||||
/// Number format ids assigned so far (inline `x14:dxf` formats); `styles.xml` adds the rest.
|
||||
pub num_fmts: crate::styles::NumFmts,
|
||||
/// Excel 2010 conditional format rules written so far (each needs a unique id).
|
||||
pub x14_cf_rules: u32,
|
||||
pub sst: Sst,
|
||||
pub images: u32,
|
||||
/// Media parts written so far, by extension and SHA-256 of their bytes: a picture used again
|
||||
@@ -181,6 +185,12 @@ pub fn person_guid(i: usize) -> String {
|
||||
format!("{{00000000-0000-4000-8002-{:012X}}}", i as u64 & 0xFFFF_FFFF_FFFF)
|
||||
}
|
||||
|
||||
/// Id of the i-th Excel 2010 conditional format rule of the package (deterministic and unique,
|
||||
/// like [`person_guid`]).
|
||||
pub fn x14_cf_rule_guid(i: u32) -> String {
|
||||
format!("{{00000000-0000-4000-8003-{i:012X}}}")
|
||||
}
|
||||
|
||||
/// `$A$1:$D$20` (or `$1:$3` / `$A:$C`).
|
||||
pub fn abs_range(r: &RangeRef) -> String {
|
||||
let c = |col: u32| gridcraft_core::col_to_letters(col);
|
||||
@@ -264,6 +274,8 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s
|
||||
overrides: vec![],
|
||||
defaults: BTreeMap::new(),
|
||||
dxfs: vec![],
|
||||
num_fmts: Default::default(),
|
||||
x14_cf_rules: 0,
|
||||
sst: Sst::default(),
|
||||
images: 0,
|
||||
media: HashMap::new(),
|
||||
@@ -367,7 +379,7 @@ pub fn write_xlsx_named_with(wb: &Workbook, kind: XlsxKind, book_name: Option<&s
|
||||
w.push_str("</workbook>");
|
||||
|
||||
// Workbook-level parts.
|
||||
let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb));
|
||||
let (styles, fmt_ids) = crate::styles::write_styles(wb, &out.dxfs, &pivots.number_formats(wb), std::mem::take(&mut out.num_fmts));
|
||||
pivots.finish(wb, &mut out, &|code: &str| crate::tables::builtin_id(code).or_else(|| fmt_ids.get(code).copied()));
|
||||
out.part("xl/styles.xml", Some("application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"), styles.into_bytes());
|
||||
wb_rels.add("styles", "styles.xml");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Chart parity
|
||||
|
||||
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-07 · **Change:** minor (chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-11-16 · **Change:** minor (a selected chart outlines its series names, category labels and values in Excel's colours, and dragging a corner of the values outline changes the plotted block, #4389, #4390; earlier: chart-data-table keys pass the series index to the shared combo plot-kind rule, restoring compilation after #1150; earlier: doughnut charts: every series is a concentric ring, the first series innermost; hole size and first slice angle kept; rotated slices cover their own sweep; legend names categories; earlier: charts resize from eight handles, chart data tables, legend keys and borders, native XLSX round-trip and print/PDF; earlier: selected chart source outlines stay beneath floating objects) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Excel's chart types and chart elements against GridCraft. Part of
|
||||
[target-app-parity.md](target-app-parity.md). **Breadth ~50%, ready ~30%, 40–60 h** (estimated).
|
||||
@@ -40,7 +40,8 @@ Sources: `crates/model/src/features.rs` (`ChartKind`, `Chart`, `Series`), `crate
|
||||
| Element | Excel | GridCraft |
|
||||
|---|---|---|
|
||||
| Move and resize the chart object | yes | yes (eight handles, each moving only its own edges; Format Chart Area Size fields) (#190) |
|
||||
| Selected chart source-data outline | visible on uncovered cells, beneath floating objects | painted above cells and below charts, shapes, pictures and slicers; retains pane clipping and right-to-left cell geometry (#2861) |
|
||||
| Selected chart source-data outline | visible on uncovered cells, beneath floating objects | painted above cells and below charts, shapes, pictures and slicers; retains pane clipping and right-to-left cell geometry (#2861); series names red, category labels purple, values one blue block (#4390); series that are not one block keep a blue outline per series |
|
||||
| Drag the source-data outline to change the chart's data | corner handles on the outline resize the plotted range | the values outline's four corners show resize cursors; a drag previews the block and the release runs `chart.setValuesRange` as one undo step: series keep their formatting, a wider block adds series and a narrower one drops them, aligned names and category labels follow; Esc cancels (#4389). Moving the block by its edge and dragging the name or category outlines are not done |
|
||||
| Chart title, axis titles | text, linked to cells, full formatting | text only |
|
||||
| Legend | position, overlay, formatting, per-entry delete | position only |
|
||||
| Data labels | value, category, series, percentage, from cells, callouts, position | one on/off flag |
|
||||
@@ -107,6 +108,7 @@ are (#1686). Such series get no `numCache`/`strCache` on save (#1690).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-16 | minor | A selected chart outlines its series names (red), category labels (purple) and values (one blue block), and the values outline has corner handles: dragging one changes the block the series plot through the new `chart.setValuesRange` command, keeping each series' formatting (#4389, #4390). Engine and real-input UI tests cover growing, shrinking, adding series, undo and Esc. No readiness score change. |
|
||||
| 2026-11-07 | minor | Chart-data-table keys use the shared plot-kind helper with their series index after #1150. A focused regression checks the first combo series uses a column key and later series use line keys. No readiness score change. |
|
||||
| 2026-11-02 | minor | Charts move and resize from eight handles, each moving only its own edges (#190); resizing leaves the work list (1–2 h, within the 40–60 h rounding) |
|
||||
| 2026-11-01 | minor | Chart data tables for column, bar, line, area and compatible combo charts: command/UI controls, formatted source values, blanks, grouped category headers, legend keys, independent borders, shared print/PDF rendering and native c:dTable import/export. Dense tables show a space notice; no readiness score change. |
|
||||
|
||||
@@ -80,7 +80,7 @@ past the parser's limit, and a wrapper inside the text. **Saving writes the real
|
||||
|
||||
| Format | Excel | GridCraft read | GridCraft write | Fidelity / notes | Tests |
|
||||
|---|---|---|---|---|---|
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `<controls>` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `<controls>` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `<controls>` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF (including the Excel 2010 `x14:conditionalFormattings` extension, MS-XLSX 2.4.6: `cellIs`, `expression`, `containsBlanks`/`notContainsBlanks`, `containsErrors`/`notContainsErrors`, `duplicateValues`/`uniqueValues`, `top10`, `aboveAverage` and `timePeriod` rules are read, with `xm:f` formulas and an inline `x14:dxf`; x14 data bars (beyond the solid fill a main-section data bar links to), icon sets, colour scales and the text rules `containsText`, `notContainsText`, `beginsWith` and `endsWith` are skipped with a warning and lost on save. Cell-value and formula rules referring to another sheet are written in the extension using `{78C0D931-6437-407d-A8EE-F0AAD7539E65}`; in the tested synthetic files, Excel for Mac 16.114 also wrote cross-sheet `expression` rules there and opened them without a repair prompt. Excel for Mac 16.114 stores cross-sheet `cfvo` rules for colour scales, data bars and icon sets only in x14; GridCraft writes those rules in the main section, and drops x14-only rules of those kinds on read with a warning. A rule with a 3-D span stays in the main section, since MS-XLSX 2.6.27 forbids `sheet-range-reference` in `xm:f`. Colour scale, data bar and icon set rules (whose cfvo formulas can also refer to other sheets) are always written in the main section), validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), form controls (buttons, scroll bars and spin buttons: control properties parts, `<controls>` and VML `x:ClientData`; a VML-only control is read too; a button's command, fixed input range or output cell travels in a hidden defined name and comes back only onto the same button while the file still assigns its macro, or none for a command), protection, calc settings, show objects (`workbookPr showObjects`). **Kept unchanged on save (pass-through, `passthrough.rs`):** custom document properties, ribbon customisation and add-in task panes, custom XML, links to external workbooks (never followed or refreshed), data connections, sheet query tables, printer settings (#324), other form controls (check boxes, list boxes, drop-downs; written in the same `<controls>` element and VML drawing as the modelled ones, also those only the VML drawing lists, with no `<controls>` entry), ActiveX controls, OLE objects and sheet backgrounds (with their VML shapes), and chart sheets (#727: the sheet, drawing, chart, style and colour parts are written back unchanged in their place, and left out when a sheet they plot was deleted or renamed or a worksheet took their name; they can't be edited or created); dropped when their sheet is deleted or their parts point at content GridCraft rewrites. **Not preserved:** slicers and slicer caches, timelines, data model, query tables attached to tables, sheet and workbook `extLst` entries we don't model, chart details; Strict Open XML files keep nothing. Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Legacy formula behavior | R/W | yes | yes | Formulas without dynamic-array metadata (`cm`) open with Excel's implicit `@`; implied operators are removed on save without `cm`, while explicit single-value `@` is kept as `_xlfn.SINGLE`; formulas the analyzer cannot finish are saved as read. | `roundtrip.rs`, `fixtures.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, notes (with their shown/hidden state) and threaded comments with replies, resolved state and timestamps (`threadedComments` and `persons` parts, #300), hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
| `.xlsx` Excel Workbook (transitional) | R/W, native | yes | yes | Cells, shared/array/dynamic formulas, shared strings (with their Japanese phonetic runs — ふりがな — kept through open + save: `<rPh>` offsets and readings and `<phoneticPr>` are written back next to the same string; the table holds each text once, so duplicate `<si>` items whose text is the same but whose readings differ keep only the first reading, with a warning on open), styles, themes, merges, CF, validation, tables, comments and notes, hyperlinks, names, freeze panes, outline, print settings, pictures, shapes, equations (Office Math with a plain-text fallback and the LaTeX source; Office Math from other writers read for a common subset), charts (simplified, see [chart-parity.md](chart-parity.md)), sparklines, PivotTables (caches and tables), protection, Allow Edit Ranges (`protectedRanges` with their password hashes, #307), calc settings, show objects (`workbookPr showObjects`). **Not preserved:** unmodelled parts and extensions (form controls, slicer caches, timelines, external links, OLE objects, custom XML, data model, query tables, chart details). Never checked in Excel across a corpus: repair prompts unknown. 100 MB files fail (#175) A picture used on several sheets is written once (#985). | `roundtrip.rs`, `fixtures.rs`, `malformed.rs`, `pivot_tests.rs` |
|
||||
@@ -221,6 +221,8 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here.
|
||||
| 2026-10-14 | minor | PDF export writes clickable annotations for safe cell URLs and destinations on printed pages; CLI `convert` accepts `.pdf` output (#954) |
|
||||
| 2026-10-13 | minor | Legacy vs dynamic-array formulas: no `cm` reads as legacy (implicit `@` inserted), implied `@` written back without `cm` |
|
||||
| 2026-10-13 | trivial | XLSX export keeps a picture shared by several sheets as one media part (#985) |
|
||||
| 2026-10-14 | trivial | Formula parser: text longer than Excel's 8,192 characters, and postfix chains (`1%%%…`, `f(1)(1)…`) past the 256-level nesting limit, are parse errors (the cell keeps its formula text and cached value) instead of trees deep enough to overflow the stack when a hostile file is opened, saved or dropped |
|
||||
| 2026-10-13 | minor | XLSX: Excel 2010 conditional formats (`x14:conditionalFormattings`) are read (`cellIs`, `expression`, blanks, errors, duplicate/unique, top 10, above average and time period rules with inline `x14:dxf`, priorities merged with the main section; data bars beyond a main-section bar's solid fill, icon sets, colour scales and the four text rules are still skipped with a warning) and cell-value and formula rules referring to another sheet (not a 3-D span) are written back in that extension, following a LibreOffice-saved file; Excel for Mac 16.114 puts cross-sheet formula (`expression`) rules there too (synthetic files; GridCraft's open with no repair prompt). Colour scale, data bar and icon set cfvo formulas referring to another sheet stay in the main section: Excel 16.114 keeps them only in x14, and opens GridCraft's main-section ones without a repair prompt. Before, these rules were skipped with a warning |
|
||||
| 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) |
|
||||
| 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) |
|
||||
| 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) |
|
||||
|
||||
@@ -111,7 +111,10 @@ assertions each, but there is no conformance suite against Excel-computed result
|
||||
reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past the used range
|
||||
(#137, and past 16,384 cells #1010, fixed 10-14 for bounded references), ROUND at 15 digits and DATE(1900,2,29) (fixed 10-09), SUMIF sum-range sizing (fixed
|
||||
10-09). Statistical distributions and financial functions with iterative solvers (RATE, IRR,
|
||||
XIRR, YIELD) are the highest-risk for last-digit differences.
|
||||
XIRR, YIELD) are the highest-risk for last-digit differences. RATE follows Excel's own iteration, reconstructed from observation (secant from the guess and the guess ± 0.001, at most 200 steps,
|
||||
stop within 1e-7 by step and value, a looser 1e-4 check after 200 steps), so it returns the same
|
||||
iterate as Excel where convergence is slow (about -100% for `RATE(n,0,-pv,0)`) and `#NUM!` where
|
||||
Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7).
|
||||
|
||||
TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in
|
||||
number- and text-format test workbooks (352 TEXT cells), all match:
|
||||
@@ -178,6 +181,7 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere
|
||||
| 2026-10-14 | minor | Set precision as displayed: results, spills and typed or reformatted numbers are stored as their format shows them when the option is on (#1343) |
|
||||
| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters (sign not counted), as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, so `9.99999999999999E-09` (was `0.00000001`), but `0.0000692361330972509`. Only 15-digit positive mantissas are Excel-verified; the limit for shorter mantissas and for negatives is inferred |
|
||||
| 2026-10-14 | minor | Bounded references up to 1,048,576 cells (`D3:AZ400`) keep their full shape instead of stopping at the used range, so `SUMPRODUCT(D3:AZ400*B3:B400,(A3:A400=x)*(D1:AZ1=y))` broadcasts like Excel and `ROWS`, `COUNTBLANK` and `--(r="")` count the blanks; references that run to the edge of the sheet (`A:A`) still stop at the used range (#1010) |
|
||||
| 2026-10-14 | minor | RATE follows Excel's iteration (secant, 200 steps, 1e-7 by step and value): `RATE(5,0,-100,0)` is -0.999999409145182 like Excel instead of `#NUM!`, `RATE(4,0,-0.0001,100)` is `#NUM!` like Excel instead of 30.62 |
|
||||
| 2026-10-13 | minor | Legacy formulas from files (no dynamic-array metadata) evaluate with implicit intersection: cells differing from Excel's cached values 68,964 → 49,866 across 4,224 test-corpus workbooks (none gets more) |
|
||||
| 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) |
|
||||
| 2026-10-12 | minor | GETPIVOTDATA added: 514 / 523 by name, 505 working |
|
||||
|
||||
+10
-3
@@ -35,9 +35,15 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
|
||||
### 3. Some unmodelled XLSX content is dropped on save (FF)
|
||||
- **Missing:** slicers and their caches, timelines, the data model, query tables attached to
|
||||
tables, unmodelled `extLst` entries, chart details. Pass-through (#330) keeps custom XML,
|
||||
external links, connections, sheet query tables, printer settings, form and ActiveX controls,
|
||||
OLE objects and sheet backgrounds; never checked in Excel (repair prompts unknown).
|
||||
tables, unmodelled `extLst` entries (among them x14 data bar settings beyond a solid fill,
|
||||
icon sets, colour scales and the text rules containsText, notContainsText, beginsWith and
|
||||
endsWith), chart details. Pass-through (#330) keeps custom XML, external links, connections,
|
||||
sheet query tables, printer settings, form and ActiveX controls, OLE objects and sheet
|
||||
backgrounds; x14-only colour-scale, data-bar and icon-set rules with cross-sheet `cfvo` are
|
||||
still dropped on read with a warning, while the other Excel 2010 conditional format rules
|
||||
(including cross-sheet cell-value and expression rules) are read and written. In tested
|
||||
synthetic files, Excel for Mac 16.114 stored cross-sheet expression and `cfvo` rules in x14;
|
||||
GridCraft-written main-section cfvo files opened without a repair prompt.
|
||||
- **Evidence:** `crates/xlsx/src/passthrough.rs` (what is kept, and why the rest isn't).
|
||||
- **Impact:** open-edit-save still simplifies workbooks with slicers, timelines or Power Pivot.
|
||||
- **Estimate:** 6–10 h. [file-format-parity.md](file-format-parity.md)
|
||||
@@ -207,6 +213,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha-
|
||||
| 2026-10-17 | minor | §6: the five reports it tracked are closed and their PRs merged (#57, #133, #139, #140, #134; PRs #148, #155, #156, #157); the entry stays open for §15's oracle suite |
|
||||
| 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" |
|
||||
| 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) |
|
||||
| 2026-10-13 | minor | §3: Excel 2010 conditional formats (`x14:conditionalFormattings`, cross-sheet rules) read, evaluated and written back in the extension |
|
||||
| 2026-10-13 | trivial | §4: multi-level category axes landed |
|
||||
| 2026-10-12 | minor | §9: next/previous sheet commands retain the current visible sheet and selection when there is no visible destination |
|
||||
| 2026-10-12 | minor | §8, §15: GETPIVOTDATA added (9 functions missing) |
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
# UI parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (Find and Replace keeps workbook Undo/Redo available while a button has keyboard focus; text fields keep their own Undo; earlier: punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4
|
||||
|
||||
Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md).
|
||||
**UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured
|
||||
@@ -275,6 +275,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12.
|
||||
| 2026-11-04 | minor | Preserve leading and trailing blank lines in wrapped cells when calculating vertical alignment; regression covers single, multiple and all-empty lines |
|
||||
| 2026-11-04 | minor | Align wrapped and unwrapped cells with the same vertical margins; regressions compare numbers with mixed CJK/Latin text, including explicit line breaks |
|
||||
| 2026-11-02 | minor | Form controls: buttons, sliders (scroll bars) and spin buttons placed, worked, selected and edited on the sheet (Insert › Controls, Assign Action, Format Control); catalog 281 / 296 |
|
||||
| 2026-11-03 | minor | Find and Replace: workbook Undo/Redo works with a keyboard-focused button; focused text fields keep text-editing Undo, and a modal message blocks workbook shortcuts. Regression covers Replace All, both Redo shortcuts, actual text undo, and an error message |
|
||||
| 2026-11-03 | minor | Highlight the active cell's row: a global preference that tints the whole row, off by default |
|
||||
| 2026-11-03 | minor | The formula bar's bottom edge is a resize handle: dragging it sets the bar's height in whole lines, up to half the window, and dragging it to one line collapses it; expanding (the chevron, Ctrl+Shift+U) returns to the dragged height, which is kept with the UI preferences. `view.expandFormulaBar {lines}` sets it (#1246) |
|
||||
| 2026-11-03 | minor | Cell context menu on a cell with a link: Edit Hyperlink… (the link dialog, titled Edit Hyperlink and filled with the link), Open Hyperlink and Remove Hyperlink, as in Excel, instead of Link… (#2120) |
|
||||
|
||||
Reference in new issue
Block a user