diff --git a/Cargo.lock b/Cargo.lock index b38e2e6c0..d15abdc5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -940,20 +940,9 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" +source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0" 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=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288" -dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)", "kurbo", "log", "serde", @@ -1063,21 +1052,10 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288" +source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", - "log", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-opc" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" -dependencies = [ - "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)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)", "log", "thiserror 2.0.21", ] @@ -1109,12 +1087,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c85293 [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" +source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0" [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288" +source = "git+https://github.com/storytold/craft-libs?rev=3b8e426a260695af840a2cd79a064d40778f939e#3b8e426a260695af840a2cd79a064d40778f939e" [[package]] name = "craft-stream-codecs" @@ -1229,12 +1207,12 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288" +source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0" dependencies = [ - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", - "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", - "craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288)", + "craft-drawingml", + "craft-opc", + "craft-sheet 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)", "thiserror 2.0.21", ] @@ -1251,17 +1229,7 @@ dependencies = [ [[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", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288" +source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1290,17 +1258,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=512a1b8e8b59a7b325e7f69f6131aa8628470288#512a1b8e8b59a7b325e7f69f6131aa8628470288" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip 9.1.0", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" +source = "git+https://github.com/storytold/craft-libs?rev=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0#0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2539,14 +2497,14 @@ version = "0.19.1" dependencies = [ "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-drawingml", "craft-math", "craft-ods", "craft-offcrypto", - "craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280)", + "craft-opc", "craft-xls", "craft-xlsx", - "craft-xml 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=0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0)", "gridcraft-core", "gridcraft-formula", "gridcraft-functions", diff --git a/Cargo.toml b/Cargo.toml index aa67ad40d..c99eef05f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f 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" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", 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" } @@ -47,11 +47,11 @@ craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9 # 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 and XLSB package/record parsing; workbook model mapping stays in gridcraft-xlsx. -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "512a1b8e8b59a7b325e7f69f6131aa8628470288", version = "0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } +# SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx. +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", version = "0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", 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" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0", version = "0.1.0" } craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c", version = "=0.1.0" } # foundation diff --git a/crates/xlsx/src/chart.rs b/crates/xlsx/src/chart.rs index fea91cec5..b603ec7f8 100644 --- a/crates/xlsx/src/chart.rs +++ b/crates/xlsx/src/chart.rs @@ -3,64 +3,143 @@ use std::fmt::Write as _; +use craft_drawingml::chart::{Chart as DmlChart, ChartType, Trendline as DmlTrendline, TrendlineType}; +use craft_drawingml::color::SchemeSlot; +use craft_drawingml::style::{ColorBase, ColorRef as DmlColor, Fill as DmlFill}; use gridcraft_core::{RangeRef, Value, category_levels}; use gridcraft_formula::{Expr, SheetSel}; -use gridcraft_model::{Chart, ChartKind, Color, DefinedName, LegendPos, LineDash, Series, Trendline, TrendlineKind, Workbook}; +use gridcraft_model::{Chart, ChartDataTable, ChartKind, Color, DefinedName, LegendPos, LineDash, Series, Trendline, TrendlineKind, Workbook}; use crate::drawing::{dml_color, srgb}; use crate::xml::{El, esc, num}; // ---------------------------------------------------------------- reading -fn group_kind(g: &El) -> Option { - let grouping = g.child_val("grouping").unwrap_or("standard"); - let stacked = grouping == "stacked"; - let pct = grouping == "percentStacked"; - Some(match g.name.as_str() { - "barChart" | "bar3DChart" => { - let bar = g.child_val("barDir") == Some("bar"); - match (bar, stacked, pct) { - (false, true, _) => ChartKind::ColumnStacked, - (false, _, true) => ChartKind::ColumnStacked100, - (false, _, _) => ChartKind::ColumnClustered, - (true, true, _) => ChartKind::BarStacked, - (true, _, true) => ChartKind::BarStacked100, - (true, _, _) => ChartKind::BarClustered, - } +pub(crate) fn to_craft_el(e: &El) -> craft_xml::El { + let mut out = craft_xml::El::new(e.name.as_str()); + out.attrs = e.attrs.clone(); + for c in &e.children { + out.children.push(craft_xml::Node::El(to_craft_el(c))); + } + if !e.text.is_empty() { + out.children.push(craft_xml::Node::Text(e.text.clone())); + } + out +} + +pub(crate) fn map_dml_color(c: &DmlColor) -> Option { + match &c.base { + ColorBase::Rgb { rgb } => Some(Color::Rgb((u32::from(rgb.r) << 16) | (u32::from(rgb.g) << 8) | u32::from(rgb.b))), + ColorBase::Scheme { slot } => { + let i = match slot { + SchemeSlot::Bg1 | SchemeSlot::Lt1 => 0, + SchemeSlot::Tx1 | SchemeSlot::Dk1 => 1, + SchemeSlot::Bg2 | SchemeSlot::Lt2 => 2, + SchemeSlot::Tx2 | SchemeSlot::Dk2 => 3, + SchemeSlot::Accent1 => 4, + SchemeSlot::Accent2 => 5, + SchemeSlot::Accent3 => 6, + SchemeSlot::Accent4 => 7, + SchemeSlot::Accent5 => 8, + SchemeSlot::Accent6 => 9, + SchemeSlot::Hlink => 10, + SchemeSlot::FolHlink => 11, + SchemeSlot::PhClr => return None, + }; + Some(Color::Theme(i, 0)) } - "lineChart" | "line3DChart" => { - if stacked || pct { - ChartKind::LineStacked - } else { - let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); - let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none")); - if !group_markers || (all_none && g.kids("ser").next().is_some()) { ChartKind::Line } else { ChartKind::LineMarkers } - } + ColorBase::System { last, .. } => Some(Color::Rgb((u32::from(last.r) << 16) | (u32::from(last.g) << 8) | u32::from(last.b))), + ColorBase::Preset { .. } => None, + } +} + +fn map_chart_type(k: ChartType, plot: Option<&El>) -> ChartKind { + match k { + ChartType::Column => ChartKind::ColumnClustered, + ChartType::StackedColumn => ChartKind::ColumnStacked, + ChartType::PercentColumn => ChartKind::ColumnStacked100, + ChartType::Bar => ChartKind::BarClustered, + ChartType::StackedBar => ChartKind::BarStacked, + ChartType::PercentBar => ChartKind::BarStacked100, + ChartType::Line => { + let markers = plot + .into_iter() + .flat_map(|p| p.kids("lineChart").chain(p.kids("line3DChart"))) + .filter(|g| !matches!(g.child_val("grouping"), Some("stacked" | "percentStacked"))) + .any(|g| { + let group_markers = g.child_val("marker").is_none_or(|v| v == "1" || v == "true"); + let all_none = g.kids("ser").all(|s| s.path(&["marker", "symbol"]).and_then(|m| m.attr("val")) == Some("none")); + group_markers && !(all_none && g.kids("ser").next().is_some()) + }); + if markers { ChartKind::LineMarkers } else { ChartKind::Line } } - "pieChart" | "pie3DChart" | "ofPieChart" => ChartKind::Pie, - "doughnutChart" => ChartKind::Doughnut, - "areaChart" | "area3DChart" => { - if pct { - ChartKind::AreaStacked100 - } else if stacked { - ChartKind::AreaStacked - } else { - ChartKind::Area - } + ChartType::LineMarkers => ChartKind::LineMarkers, + ChartType::StackedLine => ChartKind::LineStacked, + ChartType::Area => ChartKind::Area, + ChartType::StackedArea => { + let pct = plot + .into_iter() + .flat_map(|p| p.kids("areaChart").chain(p.kids("area3DChart"))) + .any(|g| g.child_val("grouping") == Some("percentStacked")); + if pct { ChartKind::AreaStacked100 } else { ChartKind::AreaStacked } } - "scatterChart" => { - let no_lines = g.kids("ser").all(|s| s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some())); - if g.child_val("scatterStyle") == Some("marker") || (no_lines && g.kids("ser").next().is_some()) { - ChartKind::Scatter - } else { - ChartKind::ScatterLines - } + ChartType::Pie => ChartKind::Pie, + ChartType::Doughnut => ChartKind::Doughnut, + ChartType::Scatter => { + let marker_only = plot.and_then(|p| p.child("scatterChart")).is_some_and(|g| { + let no_lines = g.kids("ser").all(|s| s.path(&["spPr", "ln"]).is_some_and(|l| l.child("noFill").is_some())); + g.child_val("scatterStyle") == Some("marker") || (no_lines && g.kids("ser").next().is_some()) + }); + if marker_only { ChartKind::Scatter } else { ChartKind::ScatterLines } } - "bubbleChart" => ChartKind::Bubble, - "radarChart" => ChartKind::Radar, - "stockChart" => ChartKind::Stock, - _ => return None, - }) + ChartType::Bubble => ChartKind::Bubble, + ChartType::Radar | ChartType::FilledRadar => ChartKind::Radar, + ChartType::Stock => ChartKind::Stock, + ChartType::Combo => ChartKind::Combo, + _ => ChartKind::ColumnClustered, + } +} + +fn map_trendline(t: &DmlTrendline, el: Option<&El>) -> Trendline { + let kind = match t.kind { + TrendlineType::Linear => TrendlineKind::Linear, + TrendlineType::Exp => TrendlineKind::Exponential, + TrendlineType::Log => TrendlineKind::Logarithmic, + TrendlineType::Power => TrendlineKind::Power, + TrendlineType::Poly => TrendlineKind::Polynomial(t.order.unwrap_or(2).clamp(2, 6) as u8), + TrendlineType::MovingAvg => TrendlineKind::MovingAverage(t.period.unwrap_or(2).clamp(2, 255)), + }; + let ln = el.and_then(|e| e.path(&["spPr", "ln"])); + let forecast = |name: &str, dml: Option| { + Trendline::clamp_forecast(el.and_then(|e| e.child(name)).and_then(|c| c.attr_f64("val")).or(dml).unwrap_or(0.0)) + }; + Trendline { + kind, + name: t.name.clone(), + forward: forecast("forward", t.forward), + backward: forecast("backward", t.backward), + intercept: t.intercept, + display_equation: el.and_then(|e| e.child("dispEq")).map_or(t.disp_eq, |c| c.flag("val", true)), + display_r_squared: el.and_then(|e| e.child("dispRSqr")).map_or(t.disp_r_sqr, |c| c.flag("val", true)), + color: ln.and_then(|l| l.child("solidFill")).and_then(dml_color), + width: ln.and_then(|l| l.attr_f64("w")).map(|w| (w / EMU_PER_PT) as f32).filter(|w| w.is_finite() && *w >= 0.0), + dash: ln.and_then(|l| l.child("prstDash")).and_then(|d| d.attr("val")).and_then(|v| DASHES.iter().find(|(_, n)| *n == v).map(|(d, _)| *d)), + } +} + +fn literal_array(e: Option<&El>) -> Option { + let e = e?; + for k in ["numLit", "strLit"] { + if let Some(l) = e.child(k) { + let pts: Vec = l + .kids("pt") + .filter_map(|p| p.child("v")) + .map(|v| if k == "numLit" { v.text.trim().to_string() } else { format!("\"{}\"", v.text.replace('"', "\"\"")) }) + .collect(); + return Some(format!("{{{}}}", pts.join(","))); + } + } + None } /// Excel's file notation for "this workbook" in front of a workbook-scoped defined name. @@ -101,51 +180,6 @@ pub(crate) fn chart_ref_from_file(text: &str) -> String { out } -fn data_ref(e: Option<&El>) -> Option { - let e = e?; - for k in ["numRef", "strRef", "multiLvlStrRef"] { - if let Some(f) = e.child(k).and_then(|r| r.child("f")) { - return Some(chart_ref_from_file(&f.text)); - } - } - // Literal values become an array constant. - for k in ["numLit", "strLit"] { - if let Some(l) = e.child(k) { - let pts: Vec = l - .kids("pt") - .filter_map(|p| p.child("v")) - .map(|v| if k == "numLit" { v.text.trim().to_string() } else { format!("\"{}\"", v.text.replace('"', "\"\"")) }) - .collect(); - return Some(format!("{{{}}}", pts.join(","))); - } - } - None -} - -fn read_series(s: &El) -> Series { - let name = s - .child("tx") - .and_then(|tx| tx.path(&["strRef", "f"]).map(|f| chart_ref_from_file(&f.text)).or_else(|| tx.child("v").map(|v| v.text.clone()))); - let sp = s.child("spPr"); - let color = sp - .and_then(|p| p.child("solidFill")) - .and_then(dml_color) - .or_else(|| sp.and_then(|p| p.path(&["ln", "solidFill"])).and_then(dml_color)) - .or_else(|| s.path(&["marker", "spPr", "solidFill"]).and_then(dml_color)); - Series { - name, - categories: data_ref(s.child("cat")).or_else(|| data_ref(s.child("xVal"))), - values: data_ref(s.child("val")).or_else(|| data_ref(s.child("yVal"))).unwrap_or_default(), - bubble_sizes: data_ref(s.child("bubbleSize")), - color, - secondary: false, - kind: None, - quartiles: Default::default(), - smooth: bool_val(s, "smooth"), - trendlines: s.kids("trendline").filter_map(read_trendline).collect(), - } -} - const DASHES: [(LineDash, &str); 11] = [ (LineDash::Solid, "solid"), (LineDash::Dot, "dot"), @@ -162,132 +196,119 @@ const DASHES: [(LineDash, &str); 11] = [ const EMU_PER_PT: f64 = 12_700.0; -/// A `CT_Boolean` child (`val` defaults to true). -fn bool_val(e: &El, tag: &str) -> bool { - e.child(tag).is_some_and(|c| c.flag("val", true)) -} - -fn f64_val(e: &El, tag: &str) -> Option { - e.child(tag).and_then(|c| c.attr_f64("val")) -} - -/// `` (ECMA-376 Part 1, 21.2.2.211). Unknown types are dropped. -fn read_trendline(t: &El) -> Option { - let kind = match t.child_val("trendlineType").unwrap_or("linear") { - "linear" => TrendlineKind::Linear, - "exp" => TrendlineKind::Exponential, - "log" => TrendlineKind::Logarithmic, - "power" => TrendlineKind::Power, - "poly" => TrendlineKind::Polynomial(t.child_val("order").and_then(|v| v.trim().parse::().ok()).unwrap_or(2).clamp(2, 6)), - "movingAvg" => TrendlineKind::MovingAverage(t.child_val("period").and_then(|v| v.trim().parse::().ok()).unwrap_or(2).clamp(2, 255)), - _ => return None, - }; - let ln = t.path(&["spPr", "ln"]); - Some(Trendline { - kind, - name: t.child("name").map(|n| n.text.clone()), - forward: Trendline::clamp_forecast(f64_val(t, "forward").unwrap_or(0.0)), - backward: Trendline::clamp_forecast(f64_val(t, "backward").unwrap_or(0.0)), - intercept: f64_val(t, "intercept"), - display_equation: bool_val(t, "dispEq"), - display_r_squared: bool_val(t, "dispRSqr"), - color: ln.and_then(|l| l.child("solidFill")).and_then(dml_color), - width: ln.and_then(|l| l.attr_f64("w")).map(|w| (w / EMU_PER_PT) as f32).filter(|w| w.is_finite() && *w >= 0.0), - dash: ln.and_then(|l| l.child("prstDash")).and_then(|d| d.attr("val")).and_then(|v| DASHES.iter().find(|(_, n)| *n == v).map(|(d, _)| *d)), - }) -} - -fn rich_title(t: &El) -> Option { - let tx = t.child("tx")?; - if let Some(rich) = tx.child("rich") { - let paras: Vec = - rich.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::()).collect(); - let s = paras.join("\n"); - return if s.is_empty() { None } else { Some(s) }; +pub(crate) fn from_dml_chart(dc: DmlChart, root: Option<&El>) -> Chart { + let plot = root.and_then(|r| r.path(&["chart", "plotArea"])); + let groups: Vec<&El> = plot.map(|p| p.children.iter().filter(|g| g.name.ends_with("Chart")).collect()).unwrap_or_default(); + fn ax_ids(g: &El) -> Vec<&str> { + g.kids("axId").filter_map(|a| a.attr("val")).collect() } - if let Some(sr) = tx.child("strRef") { - if let Some(v) = sr.path(&["strCache", "pt", "v"]) { - return Some(v.text.clone()); - } - return sr.child("f").map(|f| f.text.trim().to_string()); - } - None -} - -fn axis_ids(g: &El) -> Vec { - g.kids("axId").filter_map(|a| a.attr("val")).map(str::to_string).collect() -} - -pub fn read_chart(root: &El) -> Option { - let chart = root.child("chart")?; - let plot = chart.child("plotArea")?; - let groups: Vec<(&El, ChartKind)> = plot.children.iter().filter_map(|g| group_kind(g).map(|k| (g, k))).collect(); - let (first, first_kind) = *groups.first()?; - let first_axes = axis_ids(first); - let mut series = vec![]; - for (gi, (g, k)) in groups.iter().enumerate() { - for s in g.kids("ser") { - let mut ser = read_series(s); - if groups.len() > 1 { - // Every series of a combo chart keeps its own group's kind, the first group's included. - ser.kind = Some(*k); + let first_axes = groups.first().map(|g| ax_ids(g)).unwrap_or_default(); + let ser_els: Vec<(&El, bool)> = groups + .iter() + .enumerate() + .flat_map(|(gi, g)| { + let sec = gi > 0 && ax_ids(g) != first_axes; + g.kids("ser").map(move |s| (s, sec)) + }) + .collect(); + let multi_axis = ser_els.iter().any(|(_, sec)| *sec); + let is_combo = dc.kind == ChartType::Combo || multi_axis; + let base_kind = map_chart_type(dc.kind, plot); + let kind = if is_combo { ChartKind::Combo } else { base_kind }; + let series_labels = dc.series.iter().any(|s| s.data_labels == Some(true)); + let series = dc + .series + .into_iter() + .enumerate() + .map(|(i, s)| { + let (sel, fallback_sec) = match ser_els.get(i).copied() { + Some((el, sec)) => (Some(el), sec), + None => (None, false), + }; + let color = s + .fill + .as_ref() + .and_then(|f| match f { + DmlFill::Solid { color } => map_dml_color(color), + _ => None, + }) + .or_else(|| { + s.line.as_ref().and_then(|l| l.fill.as_ref()).and_then(|f| match f { + DmlFill::Solid { color } => map_dml_color(color), + _ => None, + }) + }) + .or_else(|| sel.and_then(|e| e.path(&["marker", "spPr", "solidFill"])).and_then(dml_color)); + Series { + name: s.refs.name.as_deref().map(chart_ref_from_file).or_else(|| (!s.name.is_empty()).then_some(s.name)), + categories: s + .refs + .categories + .as_deref() + .map(chart_ref_from_file) + .or_else(|| literal_array(sel.and_then(|e| e.child("cat").or_else(|| e.child("xVal"))))), + values: s + .refs + .values + .as_deref() + .map(chart_ref_from_file) + .or_else(|| literal_array(sel.and_then(|e| e.child("val").or_else(|| e.child("yVal"))))) + .unwrap_or_default(), + bubble_sizes: s.refs.sizes.as_deref().map(chart_ref_from_file).or_else(|| literal_array(sel.and_then(|e| e.child("bubbleSize")))), + color, + secondary: is_combo && (s.secondary_axis || fallback_sec), + kind: if dc.kind == ChartType::Combo { + s.kind.map(|k| map_chart_type(k, plot)) + } else if multi_axis { + Some(s.kind.map(|k| map_chart_type(k, plot)).unwrap_or(base_kind)) + } else { + None + }, + quartiles: Default::default(), + smooth: sel.map_or(s.smooth, |e| e.child("smooth").is_some_and(|c| c.flag("val", true))), + trendlines: s.trendlines.iter().enumerate().map(|(ti, t)| map_trendline(t, sel.and_then(|e| e.kids("trendline").nth(ti)))).collect(), } - if gi > 0 { - ser.secondary = axis_ids(g) != first_axes; - } - series.push(ser); - } - } - let kind = if groups.len() > 1 { ChartKind::Combo } else { first_kind }; - let show_val = |e: &El| e.child("dLbls").is_some_and(|d| bool_val(d, "showVal")); - let data_labels = groups.iter().any(|(g, _)| show_val(g) || g.kids("ser").any(show_val)); - let val_axes: Vec<&El> = plot.kids("valAx").collect(); - let cat_ax = plot.child("catAx").or_else(|| plot.child("dateAx")); - let scatter = matches!(first_kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble); - let (x_ax, y_ax) = if scatter { - let x = val_axes.iter().find(|a| matches!(a.child_val("axPos"), Some("b") | Some("t"))).copied(); - let y = val_axes.iter().find(|a| matches!(a.child_val("axPos"), Some("l") | Some("r"))).copied(); - (x, y) - } else { - (cat_ax, val_axes.first().copied()) - }; - let legend = match chart.child("legend") { + }) + .collect(); + let legend = match dc.legend.as_deref() { None => LegendPos::None, - Some(l) => match l.child_val("legendPos").unwrap_or("r") { - "b" => LegendPos::Bottom, - "t" => LegendPos::Top, - "l" => LegendPos::Left, - _ => LegendPos::Right, - }, + Some("b") => LegendPos::Bottom, + Some("t") => LegendPos::Top, + Some("l") => LegendPos::Left, + Some(_) => LegendPos::Right, }; - let doughnut = plot.child("doughnutChart"); - let hole_size = doughnut.and_then(|g| g.child_val("holeSize")).and_then(|v| v.trim().parse::().ok()).unwrap_or(75).clamp(10, 90); - let first_slice_angle = - plot.child("pieChart").or(doughnut).and_then(|g| g.child_val("firstSliceAng")).and_then(|v| v.trim().parse::().ok()).unwrap_or(0) % 360; - Some(Chart { + let hole_size = + if plot.is_some_and(|p| p.child("doughnutChart").is_some()) { (dc.hole_size * 100.0).round().clamp(10.0, 90.0) as u8 } else { 75 }; + Chart { id: 0, kind, anchor: Default::default(), - title: chart.child("title").and_then(rich_title), + title: dc.title, series, legend, - data_labels, - data_table: plot.child("dTable").map(|t| gridcraft_model::ChartDataTable { - show_keys: bool_val(t, "showKeys"), - horizontal_border: bool_val(t, "showHorzBorder"), - vertical_border: bool_val(t, "showVertBorder"), - outline: bool_val(t, "showOutline"), + data_labels: dc.data_labels || series_labels, + data_table: dc.data_table.map(|t| ChartDataTable { + show_keys: t.show_keys, + horizontal_border: t.horizontal_border, + vertical_border: t.vertical_border, + outline: t.outline, }), - gridlines: val_axes.iter().any(|a| a.child("majorGridlines").is_some()), - style: root.child_val("style").and_then(|v| v.parse().ok()).unwrap_or(2), + gridlines: dc.gridlines, + style: dc.style, hole_size, - first_slice_angle, - x_title: x_ax.and_then(|a| a.child("title")).and_then(rich_title), - y_title: y_ax.and_then(|a| a.child("title")).and_then(rich_title), + first_slice_angle: dc.first_slice_angle, + x_title: dc.axis_titles.0, + y_title: dc.axis_titles.1, source: None, by_rows: false, - pivot: root.path(&["pivotSource", "name"]).map(|n| strip_book(n.text.trim()).to_string()).filter(|n| !n.is_empty()), - }) + pivot: dc.pivot_source.as_deref().map(strip_book).filter(|n| !n.is_empty()).map(str::to_string), + } +} + +pub fn read_chart(root: &El) -> Option { + let craft = to_craft_el(root); + let dc = craft_drawingml::chart::read::chart_from(&craft)?; + Some(from_dml_chart(dc, Some(root))) } // ---------------------------------------------------------------- writing diff --git a/crates/xlsx/src/chartex.rs b/crates/xlsx/src/chartex.rs index d90ed3505..e7f5ce91e 100644 --- a/crates/xlsx/src/chartex.rs +++ b/crates/xlsx/src/chartex.rs @@ -8,7 +8,7 @@ use gridcraft_core::RangeRef; use gridcraft_formula::{Expr, SheetSel}; use gridcraft_model::{Chart, ChartKind, LegendPos, QuartileMethod, Series, Workbook}; -use crate::drawing::{dml_color, srgb}; +use crate::drawing::srgb; use crate::xml::{El, esc, esc_attr}; pub const CT_CHARTEX: &str = "application/vnd.ms-office.chartex+xml"; @@ -43,24 +43,12 @@ pub fn requires(k: ChartKind) -> (&'static str, &'static str) { // ---------------------------------------------------------------- reading -fn kind_of(layout: &str) -> Option { - Some(match layout { - "clusteredColumn" | "paretoLine" => ChartKind::Histogram, - "boxWhisker" => ChartKind::BoxWhisker, - "waterfall" => ChartKind::Waterfall, - "funnel" => ChartKind::Funnel, - "treemap" => ChartKind::Treemap, - "sunburst" => ChartKind::Sunburst, - _ => return None, - }) -} - -fn formula(dim: &El) -> Option { +fn chartex_formula(dim: &El) -> Option { let f = dim.child("f")?; Some(crate::fmla::from_file(&crate::chart::chart_ref_from_file(&f.text))) } -fn text(tx: &El) -> Option { +fn chartex_text(tx: &El) -> Option { if let Some(d) = tx.child("txData") { if let Some(f) = d.child("f") { return Some(crate::chart::chart_ref_from_file(&f.text)); @@ -73,85 +61,124 @@ fn text(tx: &El) -> Option { if s.is_empty() { None } else { Some(s) } } -pub fn read_chartex(root: &El) -> Option { - let chart = root.child("chart")?; - let plot = chart.child("plotArea")?; - let region = plot.child("plotAreaRegion")?; - // Data by id: (categories, values). +pub(crate) fn from_dml_chartex(dc: craft_drawingml::chart::Chart, root: Option<&El>) -> Option { + use craft_drawingml::chart::ChartType; + let kind = match dc.kind { + ChartType::Histogram | ChartType::Pareto => ChartKind::Histogram, + ChartType::BoxWhisker => ChartKind::BoxWhisker, + ChartType::Waterfall => ChartKind::Waterfall, + ChartType::Funnel => ChartKind::Funnel, + ChartType::Treemap => ChartKind::Treemap, + ChartType::Sunburst => ChartKind::Sunburst, + _ => return None, + }; + let default_quartiles = if dc.inclusive_quartiles { QuartileMethod::Inclusive } else { QuartileMethod::Exclusive }; let data: Vec<(String, Option, Option)> = root - .child("chartData") + .and_then(|r| r.child("chartData")) .map(|cd| { cd.kids("data") .map(|d| { let id = d.attr("id").unwrap_or("").to_string(); - let cat = d.kids("strDim").chain(d.kids("numDim")).find(|x| matches!(x.attr("type"), Some("cat" | "x"))).and_then(formula); - let val = d.kids("numDim").find(|x| matches!(x.attr("type"), Some("val" | "size" | "y"))).and_then(formula); + let cat = + d.kids("strDim").chain(d.kids("numDim")).find(|x| matches!(x.attr("type"), Some("cat" | "x"))).and_then(chartex_formula); + let val = d.kids("numDim").find(|x| matches!(x.attr("type"), Some("val" | "size" | "y"))).and_then(chartex_formula); (id, cat, val) }) .collect() }) .unwrap_or_default(); - let mut kind = None; - let mut series = vec![]; - let mut data_labels = false; - for s in region.kids("series") { - let layout = s.attr("layoutId").unwrap_or(""); - // A Pareto line belongs to its histogram. - if layout == "paretoLine" { - continue; - } - let k = kind_of(layout)?; - kind.get_or_insert(k); - let id = s.child_val("dataId").unwrap_or(""); - let (cat, val) = data.iter().find(|(i, _, _)| i == id).map(|(_, c, v)| (c.clone(), v.clone())).unwrap_or_default(); - data_labels |= s.path(&["dataLabels", "visibility"]).is_some_and(|v| v.flag("value", false)); - series.push(Series { - quartiles: match s.path(&["layoutPr", "statistics"]).and_then(|el| el.attr("quartileMethod")) { - Some("inclusive") => QuartileMethod::Inclusive, - _ => QuartileMethod::Exclusive, - }, - name: s.child("tx").and_then(text), - categories: cat, - values: val.unwrap_or_default(), - // The default colour (the series' theme accent, which the writer spells out) isn't kept. - color: s - .path(&["spPr", "solidFill"]) - .and_then(dml_color) - .filter(|c| *c != gridcraft_model::Color::Theme(4 + (series.len() % 6) as u8, 0)), - ..Default::default() - }); - } - let legend = match chart.child("legend") { + let series_els: Vec<&El> = root + .and_then(|r| r.path(&["chart", "plotArea", "plotAreaRegion"])) + .map(|region| region.kids("series").filter(|s| s.attr("layoutId") != Some("paretoLine")).collect()) + .unwrap_or_default(); + let series = dc + .series + .into_iter() + .enumerate() + .map(|(idx, s)| { + let sel = series_els.get(idx).copied(); + let (cat, val) = sel + .and_then(|el| el.child_val("dataId")) + .and_then(|id| data.iter().find(|(i, _, _)| i == id)) + .map(|(_, c, v)| (c.clone(), v.clone())) + .unwrap_or_default(); + let color = s + .fill + .as_ref() + .and_then(|f| match f { + craft_drawingml::style::Fill::Solid { color } => crate::chart::map_dml_color(color), + _ => None, + }) + .or_else(|| sel.and_then(|el| el.path(&["spPr", "solidFill"])).and_then(crate::drawing::dml_color)) + .filter(|c| *c != gridcraft_model::Color::Theme(4 + (idx % 6) as u8, 0)); + let quartiles = sel + .and_then(|el| el.path(&["layoutPr", "statistics"])) + .and_then(|st| st.attr("quartileMethod")) + .map(|m| if m == "inclusive" { QuartileMethod::Inclusive } else { QuartileMethod::Exclusive }) + .unwrap_or(default_quartiles); + let name = sel + .and_then(|el| el.child("tx")) + .and_then(chartex_text) + .or_else(|| s.refs.name.as_deref().map(crate::chart::chart_ref_from_file)) + .or_else(|| (!s.name.is_empty()).then_some(s.name)); + let categories = cat.or_else(|| s.refs.categories.as_deref().map(|f| crate::fmla::from_file(&crate::chart::chart_ref_from_file(f)))); + let values = + val.or_else(|| s.refs.values.as_deref().map(|f| crate::fmla::from_file(&crate::chart::chart_ref_from_file(f)))).unwrap_or_default(); + Series { quartiles, name, categories, values, color, ..Default::default() } + }) + .collect(); + let legend = match dc.legend.as_deref() { None => LegendPos::None, - Some(l) => match l.attr("pos").unwrap_or("r") { - "b" => LegendPos::Bottom, - "t" => LegendPos::Top, - "l" => LegendPos::Left, - _ => LegendPos::Right, - }, + Some("b") => LegendPos::Bottom, + Some("t") => LegendPos::Top, + Some("l") => LegendPos::Left, + Some(_) => LegendPos::Right, + }; + let axis_title = |is_val: bool| -> Option { + let pa = root?.path(&["chart", "plotArea"])?; + let ax = pa.kids("axis").find(|a| if is_val { a.child("valScaling").is_some() } else { a.child("catScaling").is_some() })?; + let title = ax.child("title")?; + if let Some(v) = title.path(&["tx", "txData", "v"]).map(|v| v.text.trim()).filter(|t| !t.is_empty()) { + return Some(v.to_string()); + } + let rich = title.path(&["tx", "rich"])?; + let text: String = rich + .kids("p") + .map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::()) + .collect::>() + .join("\n"); + (!text.trim().is_empty()).then_some(text) }; - let axis_title = |id: &str| plot.kids("axis").find(|a| a.attr("id") == Some(id)).and_then(|a| a.path(&["title", "tx"])).and_then(text); Some(Chart { id: 0, - kind: kind?, + kind, anchor: Default::default(), - title: chart.path(&["title", "tx"]).and_then(text), + title: dc.title, series, legend, - data_labels, + data_labels: dc.data_labels, data_table: None, - gridlines: plot.kids("axis").any(|a| a.child("majorGridlines").is_some()), + gridlines: dc.gridlines, style: 2, hole_size: 75, first_slice_angle: 0, - x_title: axis_title("0"), - y_title: axis_title("1"), + x_title: dc.axis_titles.0.or_else(|| axis_title(false)), + y_title: dc.axis_titles.1.or_else(|| axis_title(true)), source: None, by_rows: false, pivot: None, }) } +pub fn read_chartex(root: &El) -> Option { + let mut craft = crate::chart::to_craft_el(root); + if craft.child(craft_xml::Local("chartData")).is_none() { + craft.push(craft_xml::El::new("chartData").with_child(craft_xml::El::new("data").with_attr("id", "0"))); + } + let dc = craft_drawingml::chart::chartex::chartex_from(&craft)?; + from_dml_chartex(dc, Some(root)) +} + // ---------------------------------------------------------------- writing /// Prefix of the hidden defined names chartex formulas go through: a chartex part refers to diff --git a/crates/xlsx/src/drawing.rs b/crates/xlsx/src/drawing.rs index ea9363a83..095bfe656 100644 --- a/crates/xlsx/src/drawing.rs +++ b/crates/xlsx/src/drawing.rs @@ -8,6 +8,7 @@ use std::fmt::Write as _; +use craft_xlsx::{Anchor as CraftAnchor, Drawing as CraftDrawing, Item as CraftItem, Marker as CraftMarker, Placement as CraftPlacement}; use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS}; use gridcraft_model::{Anchor, AnchorMode, Color, Image, Shape, ShapeFormat, ShapeKind, ShapeTextAlign, ShapeTextAnchor, Sheet, Theme}; @@ -24,6 +25,10 @@ fn emu_px(v: Option) -> f32 { v.map(|e| (e as f64 / EMU_PER_PX).clamp(-1e7, 1e7) as f32).unwrap_or(0.0) } +fn emu_to_px(v: i64) -> f32 { + (v as f64 / EMU_PER_PX).clamp(-1e7, 1e7) as f32 +} + pub(crate) fn marker(e: &El) -> (CellRef, f32, f32) { let num = |n: &str| e.child(n).and_then(|c| c.text.trim().parse::().ok()); let col = num("col").unwrap_or(0).clamp(0, MAX_COLS as i64 - 1) as u32; @@ -31,56 +36,64 @@ pub(crate) fn marker(e: &El) -> (CellRef, f32, f32) { (CellRef::new(row, col), emu_px(num("colOff")).max(0.0), emu_px(num("rowOff")).max(0.0)) } -fn ext_px(e: Option<&El>) -> (f32, f32) { - match e { - Some(x) => (emu_px(x.attr_i64("cx")).max(0.0), emu_px(x.attr_i64("cy")).max(0.0)), - None => (0.0, 0.0), - } +fn craft_marker(m: CraftMarker) -> (CellRef, f32, f32) { + let col = m.col.min(MAX_COLS - 1); + let row = m.row.min(MAX_ROWS - 1); + (CellRef::new(row, col), emu_to_px(m.col_off).max(0.0), emu_to_px(m.row_off).max(0.0)) } -fn read_anchor(a: &El, sheet: &Sheet) -> Option { - match a.name.as_str() { - "twoCellAnchor" => { - let (cell, dx, dy) = marker(a.child("from")?); - let (to, tdx, tdy) = a.child("to").map(marker).unwrap_or((cell, dx, dy)); +fn placement_to_anchor(p: &CraftPlacement, sheet: &Sheet) -> Anchor { + match p { + CraftPlacement::TwoCell { from, to, edit_as } => { + let (cell, dx, dy) = craft_marker(*from); + let (to, tdx, tdy) = craft_marker(*to); let x1 = sheet.col_left(cell.col) + dx as f64; let y1 = sheet.row_top(cell.row) + dy as f64; let x2 = sheet.col_left(to.col) + tdx as f64; let y2 = sheet.row_top(to.row) + tdy as f64; - // Excel stores "Move and size with cells" as a plain twoCellAnchor, "Move but don't - // size" as editAs="oneCell", and "Don't move or size" as editAs="absolute". - let mode = match a.attr("editAs") { + let mode = match edit_as.as_deref() { Some("absolute") => AnchorMode::Absolute, Some("oneCell") => AnchorMode::MoveOnly, _ => AnchorMode::MoveAndSize, }; - Some(Anchor { cell, dx, dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode }) + Anchor { cell, dx, dy, width: (x2 - x1).max(0.0) as f32, height: (y2 - y1).max(0.0) as f32, mode } } - "oneCellAnchor" => { - let (cell, dx, dy) = marker(a.child("from")?); - let (width, height) = ext_px(a.child("ext")); - Some(Anchor { cell, dx, dy, width, height, mode: AnchorMode::MoveOnly }) + CraftPlacement::OneCell { from, cx, cy } => { + let (cell, dx, dy) = craft_marker(*from); + Anchor { cell, dx, dy, width: emu_to_px(*cx).max(0.0), height: emu_to_px(*cy).max(0.0), mode: AnchorMode::MoveOnly } } - "absoluteAnchor" => { - let pos = a.child("pos"); - let x = emu_px(pos.and_then(|p| p.attr_i64("x"))).max(0.0) as f64; - let y = emu_px(pos.and_then(|p| p.attr_i64("y"))).max(0.0) as f64; + CraftPlacement::Absolute { x, y, cx, cy } => { + let x = emu_to_px(*x).max(0.0) as f64; + let y = emu_to_px(*y).max(0.0) as f64; let col = sheet.col_at(x); let row = sheet.row_at(y); - let (width, height) = ext_px(a.child("ext")); - Some(Anchor { + Anchor { cell: CellRef::new(row, col), dx: (x - sheet.col_left(col)).max(0.0) as f32, dy: (y - sheet.row_top(row)).max(0.0) as f32, - width, - height, + width: emu_to_px(*cx).max(0.0), + height: emu_to_px(*cy).max(0.0), mode: AnchorMode::Absolute, - }) + } } - _ => None, } } +fn from_craft_el(e: &craft_xml::El) -> El { + let name = e.name.split_once(':').map_or(e.name.as_str(), |(_, local)| local).to_string(); + let attrs = e.attrs.iter().map(|(k, v)| (k.split_once(':').map_or(k.as_str(), |(_, local)| local).to_string(), v.clone())).collect(); + let mut children = Vec::new(); + let mut text = String::new(); + for node in &e.children { + match node { + craft_xml::Node::El(c) => children.push(from_craft_el(c)), + craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => text.push_str(t), + craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {} + } + } + El { name, attrs, children, text } +} + /// Colour of a DrawingML colour choice inside `e` (e.g. a `solidFill`). pub fn dml_color(e: &El) -> Option { if let Some(c) = e.child("srgbClr").and_then(|c| c.attr("val")) { @@ -127,32 +140,53 @@ fn mime_for(name: &str) -> &'static str { } pub fn read_drawing(cx: &mut Ctx<'_>, part: &str, sheet: &mut Sheet) -> Result<(), IoError> { - let Some(x) = cx.optional_xml(part)? else { return Ok(()) }; + let Some(bytes) = cx.pkg.read(part)? else { + cx.warn(format!("missing part {part}")); + return Ok(()); + }; + let opts = craft_xml::Options::canonical(&craft_xlsx::ns::CANONICAL).with_limits(craft_xml::Limits { + max_input: crate::package::MAX_PART as usize, + max_depth: crate::xml::MAX_DEPTH, + max_nodes: crate::xml::MAX_XML_NODES, + ..craft_xml::Limits::DEFAULT + }); + let root = match opts.parse(&bytes) { + Ok(r) => r, + Err(e) if e.is_limit() => return Err(IoError::TooLarge(format!("{part}: {e}"))), + Err(e) => { + cx.warn(format!("skipped {part}: {e}")); + return Ok(()); + } + }; + let dr = CraftDrawing::read(&root); let rels = cx.pkg.rels(part)?; - for (n, a) in x.children.iter().enumerate() { - let Some(anchor) = read_anchor(a, sheet) else { continue }; + let mut anchors: Vec<&CraftAnchor> = Vec::new(); + let mut alt_anchors: Vec = Vec::new(); + for item in &dr.items { + match item { + CraftItem::Anchor(a) => anchors.push(a), + CraftItem::Other(e) if e.name == "mc:AlternateContent" => { + alt_anchors.extend(CraftDrawing::alternate_anchors(e)); + } + CraftItem::Other(_) => {} + } + } + for (n, craft_a) in anchors.into_iter().chain(alt_anchors.iter()).enumerate() { + let anchor = placement_to_anchor(&craft_a.placement, sheet); let n = n + 1; - // Objects in markup-compatibility blocks: the first choice (chartex frames, or Office Math - // that converts to LaTeX), else the fallback. - let objs: Vec<&El> = a - .children - .iter() - .flat_map(|o| match o.name.as_str() { - "AlternateContent" => o - .child("Choice") - .filter(|c| { - // Office Math is taken only when the box holds one equation that - // converts: otherwise the fallback (a picture or text from the writer) - // keeps everything visible. - c.child("graphicFrame").is_some() - || c.child("sp").and_then(|sp| sp.child("txBody")).and_then(crate::omml::equation_source).is_some() - }) - .or_else(|| o.child("Fallback")) - .map(|c| c.children.iter().collect()) - .unwrap_or_default(), - _ => vec![o], - }) - .collect(); + let obj_el = from_craft_el(&craft_a.object); + let objs: Vec<&El> = match obj_el.name.as_str() { + "AlternateContent" => obj_el + .child("Choice") + .filter(|c| { + c.child("graphicFrame").is_some() + || c.child("sp").and_then(|sp| sp.child("txBody")).and_then(crate::omml::equation_source).is_some() + }) + .or_else(|| obj_el.child("Fallback")) + .map(|c| c.children.iter().collect()) + .unwrap_or_default(), + _ => vec![&obj_el], + }; for obj in objs { match obj.name.as_str() { "pic" => { @@ -475,12 +509,7 @@ fn holds_written_text(tb: &El, src: &str) -> bool { crate::xml::parse(written.as_bytes()).is_ok_and(|w| body_text(&w) == body_text(tb)) } -/// The opening `` for a model anchor, carrying Excel's `editAs` when the mode -/// is not the default: omitted for "Move and size with cells", `editAs="oneCell"` for "Move but -/// don't size", `editAs="absolute"` for "Don't move or size". (Excel writes pictures this way; -/// the standalone `oneCellAnchor`/`absoluteAnchor` elements are read on import but not written.) -/// Returns the opening tag and the matching closing tag. -fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) { +fn to_placement(sheet: &Sheet, a: &Anchor) -> CraftPlacement { let px = |v: f64| ((v.max(0.0)) * EMU_PER_PX).round() as i64; let x1 = sheet.col_left(a.cell.col) + a.dx as f64; let y1 = sheet.row_top(a.cell.row) + a.dy as f64; @@ -490,21 +519,26 @@ fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) { let tr = sheet.row_at(y2); let tdx = x2 - sheet.col_left(tc); let tdy = y2 - sheet.row_top(tr); - let edit = match a.mode { - AnchorMode::MoveAndSize => "", - AnchorMode::MoveOnly => " editAs=\"oneCell\"", - AnchorMode::Absolute => " editAs=\"absolute\"", + let edit_as = match a.mode { + AnchorMode::MoveAndSize => None, + AnchorMode::MoveOnly => Some("oneCell".to_string()), + AnchorMode::Absolute => Some("absolute".to_string()), }; - let open = format!( - "{}{}{}{}{tc}{}{tr}{}", - a.cell.col, - px(a.dx as f64), - a.cell.row, - px(a.dy as f64), - px(tdx), - px(tdy) - ); - (open, "") + CraftPlacement::TwoCell { + from: CraftMarker { col: a.cell.col, col_off: px(a.dx as f64), row: a.cell.row, row_off: px(a.dy as f64) }, + to: CraftMarker { col: tc, col_off: px(tdx), row: tr, row_off: px(tdy) }, + edit_as, + } +} + +fn parse_craft_fragment(xml: &str) -> Option { + let opts = craft_xml::Options::default().with_limits(craft_xml::Limits { + max_input: crate::package::MAX_PART as usize, + max_depth: crate::xml::MAX_DEPTH, + max_nodes: crate::xml::MAX_XML_NODES, + ..craft_xml::Limits::DEFAULT + }); + opts.parse(xml.as_bytes()).ok() } fn xfrm(a: &Anchor, tag: &str) -> String { @@ -533,151 +567,148 @@ pub enum Obj<'a> { /// The drawing part for a sheet's objects (relationship ids already assigned). pub fn write_drawing(sheet: &Sheet, theme: &Theme, objs: &[Obj<'_>]) -> String { - let mut s = String::from( - "\n", - ); + let mut items = Vec::with_capacity(objs.len()); for (i, o) in objs.iter().enumerate() { let id = i + 2; - let close_tag; match o { Obj::Image(img, rid) => { - let (open, close) = anchor_open(sheet, &img.anchor); - close_tag = close; - s.push_str(&open); - let _ = write!( - s, - "{}", - id - 1, - esc_attr(&img.alt), - xfrm(&img.anchor, "a:xfrm") - ); + let placement = to_placement(sheet, &img.anchor); + let mut anchor = CraftAnchor::picture(placement, id as u32, &format!("Picture {}", id - 1), &img.alt, rid); + if let Some(ext) = anchor.object.child_mut("xdr:spPr").and_then(|sp| sp.child_mut("a:xfrm")).and_then(|x| x.child_mut("a:ext")) { + let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64; + ext.set_attr("cx", e(img.anchor.width)); + ext.set_attr("cy", e(img.anchor.height)); + } + items.push(CraftItem::Anchor(anchor)); } Obj::Chart(ch, rid) if crate::chartex::is_chartex(ch.kind) => { - // Chartex frames come with a fallback for readers that don't know them. - let (open, close) = anchor_open(sheet, &ch.anchor); - close_tag = close; - s.push_str(&open); + let placement = to_placement(sheet, &ch.anchor); let (prefix, ns) = crate::chartex::requires(ch.kind); - let _ = write!( - s, + let xml = format!( "{}{}This chart type can't be shown by this application.", id - 1, xfrm(&ch.anchor, "xdr:xfrm"), xfrm(&ch.anchor, "a:xfrm") ); + if let Some(object) = parse_craft_fragment(&xml) { + items.push(CraftItem::Anchor(CraftAnchor { placement, object, client_data: None })); + } } Obj::Chart(ch, rid) => { - let (open, close) = anchor_open(sheet, &ch.anchor); - close_tag = close; - s.push_str(&open); - let _ = write!( - s, - "{}", - id - 1, - xfrm(&ch.anchor, "xdr:xfrm") - ); + let placement = to_placement(sheet, &ch.anchor); + let mut anchor = CraftAnchor::chart(placement, id as u32, &format!("Chart {}", id - 1), rid); + if let Some(ext) = anchor.object.child_mut("xdr:xfrm").and_then(|x| x.child_mut("a:ext")) { + let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64; + ext.set_attr("cx", e(ch.anchor.width)); + ext.set_attr("cy", e(ch.anchor.height)); + } + items.push(CraftItem::Anchor(anchor)); } Obj::Shape(sh) if sh.kind == ShapeKind::Equation => { - let (open, close) = anchor_open(sheet, &sh.anchor); - close_tag = close; - s.push_str(&open); - write_equation(&mut s, sh, id, theme); + let placement = to_placement(sheet, &sh.anchor); + let mut xml = String::new(); + write_equation(&mut xml, sh, id, theme); + if let Some(object) = parse_craft_fragment(&xml) { + items.push(CraftItem::Anchor(CraftAnchor { placement, object, client_data: None })); + } } Obj::Shape(sh) => { - let (open, close) = anchor_open(sheet, &sh.anchor); - close_tag = close; - s.push_str(&open); - if let Some(xml) = ink::write(sh, theme, id) { - s.push_str(&xml); - s.push_str(""); - s.push_str(close_tag); - continue; - } - let (prst, tx) = match sh.kind { - ShapeKind::Rectangle => ("rect", false), - ShapeKind::RoundedRectangle => ("roundRect", false), - ShapeKind::Ellipse => ("ellipse", false), - ShapeKind::Triangle => ("triangle", false), - ShapeKind::Line | ShapeKind::Arrow => ("line", false), - // Equations are written by `write_equation`; this arm keeps the match whole. - ShapeKind::TextBox | ShapeKind::WordArt | ShapeKind::Equation => ("rect", true), - ShapeKind::Icon | ShapeKind::Ink => ("rect", false), + let placement = to_placement(sheet, &sh.anchor); + let xml = if let Some(xml) = ink::write(sh, theme, id) { + xml + } else { + let mut s = String::new(); + write_plain_shape(&mut s, sh, id, theme); + s }; - let _ = write!( - s, - "{}", - id - 1, - if tx { " txBox=\"1\"" } else { "" }, - xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation) - ); - if let Some(c) = srgb(&sh.fill, theme) { - let _ = write!(s, "{c}"); + if let Some(object) = parse_craft_fragment(&xml) { + items.push(CraftItem::Anchor(CraftAnchor { placement, object, client_data: None })); } - let line_c = srgb(&sh.line, theme); - if sh.format.no_line { - s.push_str(""); - } else if line_c.is_some() || sh.kind == ShapeKind::Arrow { - s.push_str(""); - match line_c { - Some(c) => { - let _ = write!(s, "{c}"); - } - None => s.push_str(""), - } - if sh.kind == ShapeKind::Arrow { - s.push_str(""); - } - s.push_str(""); - } - s.push_str(""); - // A WordArt with no text still writes its body, which carries the WordArt marker. - if !sh.text.is_empty() || sh.kind == ShapeKind::WordArt { - let f = &sh.format; - let anchor = match f.anchor { - Some(ShapeTextAnchor::Top) => " anchor=\"t\"", - Some(ShapeTextAnchor::Middle) => " anchor=\"ctr\"", - Some(ShapeTextAnchor::Bottom) => " anchor=\"b\"", - None if sh.kind == ShapeKind::TextBox => " anchor=\"t\"", - None => "", - }; - if sh.kind == ShapeKind::WordArt { - // Our WordArt marker: a (non-warping) text warp, which the reader maps back to WordArt. - let _ = write!( - s, - "" - ); - } else { - let _ = write!(s, ""); - } - let algn = match f.align { - None => "", - Some(ShapeTextAlign::Left) => " algn=\"l\"", - Some(ShapeTextAlign::Center) => " algn=\"ctr\"", - Some(ShapeTextAlign::Right) => " algn=\"r\"", - }; - let rtl = if f.rtl { " rtl=\"1\"" } else { "" }; - let ppr = if algn.is_empty() && rtl.is_empty() { String::new() } else { format!("") }; - let (rpr_attrs, rpr_body) = run_props(f, theme); - for line in sh.text.split('\n') { - if line.is_empty() { - let _ = write!(s, "{ppr}"); - } else if rpr_body.is_empty() { - let _ = write!(s, "{ppr}{}", esc(line)); - } else { - let _ = - write!(s, "{ppr}{rpr_body}{}", esc(line)); - } - } - s.push_str(""); - } - s.push_str(""); } } - s.push_str(""); - s.push_str(close_tag); } - s.push_str(""); - s + let dr = CraftDrawing { items, attrs: Vec::new() }; + String::from_utf8_lossy(&dr.to_xml()).into_owned() +} + +fn write_plain_shape(s: &mut String, sh: &Shape, id: usize, theme: &Theme) { + let (prst, tx) = match sh.kind { + ShapeKind::Rectangle => ("rect", false), + ShapeKind::RoundedRectangle => ("roundRect", false), + ShapeKind::Ellipse => ("ellipse", false), + ShapeKind::Triangle => ("triangle", false), + ShapeKind::Line | ShapeKind::Arrow => ("line", false), + // Equations are written by `write_equation`; this arm keeps the match whole. + ShapeKind::TextBox | ShapeKind::WordArt | ShapeKind::Equation => ("rect", true), + ShapeKind::Icon | ShapeKind::Ink => ("rect", false), + }; + let _ = write!( + s, + "{}", + id - 1, + if tx { " txBox=\"1\"" } else { "" }, + xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation) + ); + if let Some(c) = srgb(&sh.fill, theme) { + let _ = write!(s, "{c}"); + } + let line_c = srgb(&sh.line, theme); + if sh.format.no_line { + s.push_str(""); + } else if line_c.is_some() || sh.kind == ShapeKind::Arrow { + s.push_str(""); + match line_c { + Some(c) => { + let _ = write!(s, "{c}"); + } + None => s.push_str(""), + } + if sh.kind == ShapeKind::Arrow { + s.push_str(""); + } + s.push_str(""); + } + s.push_str(""); + // A WordArt with no text still writes its body, which carries the WordArt marker. + if !sh.text.is_empty() || sh.kind == ShapeKind::WordArt { + let f = &sh.format; + let anchor = match f.anchor { + Some(ShapeTextAnchor::Top) => " anchor=\"t\"", + Some(ShapeTextAnchor::Middle) => " anchor=\"ctr\"", + Some(ShapeTextAnchor::Bottom) => " anchor=\"b\"", + None if sh.kind == ShapeKind::TextBox => " anchor=\"t\"", + None => "", + }; + if sh.kind == ShapeKind::WordArt { + // Our WordArt marker: a (non-warping) text warp, which the reader maps back to WordArt. + let _ = write!( + s, + "" + ); + } else { + let _ = write!(s, ""); + } + let algn = match f.align { + None => "", + Some(ShapeTextAlign::Left) => " algn=\"l\"", + Some(ShapeTextAlign::Center) => " algn=\"ctr\"", + Some(ShapeTextAlign::Right) => " algn=\"r\"", + }; + let rtl = if f.rtl { " rtl=\"1\"" } else { "" }; + let ppr = if algn.is_empty() && rtl.is_empty() { String::new() } else { format!("") }; + let (rpr_attrs, rpr_body) = run_props(f, theme); + for line in sh.text.split('\n') { + if line.is_empty() { + let _ = write!(s, "{ppr}"); + } else if rpr_body.is_empty() { + let _ = write!(s, "{ppr}{}", esc(line)); + } else { + let _ = write!(s, "{ppr}{rpr_body}{}", esc(line)); + } + } + s.push_str(""); + } + s.push_str(""); } /// A text run's `a:rPr` attributes (size, bold, italic) and children in schema order (outline, diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index d4de20c60..561dce414 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -18,6 +18,7 @@ const LIMITS: craft_opc::Limits = craft_opc::Limits::new(MAX_ENTRIES, MAX_PART, pub struct Package<'a> { opc: craft_opc::LazyPackage<'a>, + craft: craft_xlsx::Package<'a>, } /// A relationship. @@ -46,9 +47,25 @@ fn error(e: craft_opc::Error) -> IoError { } } +/// GridCraft's wording of a `craft-xlsx` error. +pub(crate) fn craft_error(e: craft_xlsx::Error) -> IoError { + match e { + craft_xlsx::Error::Zip(m) => IoError::Zip(m), + craft_xlsx::Error::Xml(m) => IoError::Xml(m), + craft_xlsx::Error::Invalid(m) => IoError::Format(m), + craft_xlsx::Error::TooLarge(m) => IoError::TooLarge(m), + } +} + impl<'a> Package<'a> { pub fn open(bytes: &'a [u8]) -> Result, IoError> { - Ok(Package { opc: craft_opc::LazyPackage::open(bytes, &LIMITS).map_err(error)? }) + let opc = craft_opc::LazyPackage::open(bytes, &LIMITS).map_err(error)?; + let craft = craft_xlsx::Package::open(bytes, &craft_xlsx::Limits::default()).map_err(craft_error)?; + Ok(Package { opc, craft }) + } + + pub(crate) fn craft_mut(&mut self) -> &mut craft_xlsx::Package<'a> { + &mut self.craft } /// Every part's (normalized) name, sorted. diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 35fd4c881..ef5ae2178 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -3,6 +3,10 @@ use std::collections::HashMap; use std::sync::Arc; +use craft_xlsx::{ + CellFormula as CraftFormula, CellValue as CraftValue, FormulaKind as CraftFormulaKind, Row as CraftRow, SheetEntry as CraftSheetEntry, + SheetKind as CraftSheetKind, SheetPart as CraftSheetPart, Visibility as CraftVisibility, +}; use gridcraft_core::date::{serial_from_ymd, time_fraction}; use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRef, Value}; use gridcraft_formula::Expr; @@ -14,7 +18,7 @@ use gridcraft_model::{ use crate::IoError; use crate::fmla::{from_file, unwrap_google_sheets}; -use crate::package::Rel; +use crate::package::{Rel, craft_error}; use crate::read::Ctx; use crate::styles::read_color; use crate::tables::{col_width_to_px, paper_name, pt_to_px}; @@ -23,8 +27,8 @@ use crate::xml::{self, El}; mod parts; mod rules; -pub use parts::{read_autofilter, read_table}; -use parts::{read_comments, read_hyperlinks, read_note_shapes, read_threaded}; +pub use parts::read_autofilter; +use parts::read_threaded; use rules::{read_cf, read_validation, read_x14_cf}; struct Shared { @@ -46,7 +50,6 @@ struct LinkBudget { #[derive(Default)] struct RowState { - next_row: u32, shared: HashMap, /// Dynamic-array spill ranges and legacy array ranges: cached values inside them (other than /// the anchor) are not stored, so the formula can fill them again. @@ -58,8 +61,6 @@ struct RowState { /// The cell being read lost its shared formula to a copy limit: its cached value is kept, even /// inside an array range (where a formula's cached values otherwise give way to the spill). shared_copy_refused: bool, - dropped: u64, - rows: u64, } /// The known dynamic range `pos` lies in, when it isn't the range's anchor: the cell's cached @@ -169,60 +170,159 @@ const MAX_DYNAMIC_CHECKS: u64 = 16_000_000; /// rule copies its element's whole range list, so rules × ranges must stay bounded. const MAX_COND_CELLS: u64 = 4_000_000; -fn read_sheet_format(e: &El, sheet: &mut Sheet) { - if let Some(h) = e.attr_f64("defaultRowHeight") { - let px = pt_to_px(h); - if px > 0.0 { - sheet.default_row_height = px; +fn from_craft_el(e: &craft_xml::El) -> El { + let name = e.name.split_once(':').map_or(e.name.as_str(), |(_, local)| local).to_string(); + let attrs = e.attrs.iter().map(|(k, v)| (k.split_once(':').map_or(k.as_str(), |(_, local)| local).to_string(), v.clone())).collect(); + let mut children = Vec::new(); + let mut text = String::new(); + for node in &e.children { + match node { + craft_xml::Node::El(c) => children.push(from_craft_el(c)), + craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => text.push_str(t), + craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {} } } - if let Some(w) = e.attr_f64("defaultColWidth") { - let px = col_width_to_px(w); - if px > 0.0 { - sheet.default_col_width = px; - } - } else if let Some(b) = e.attr_f64("baseColWidth") { - let px = ((b.clamp(0.0, 255.0) * 7.0 + 5.0) / 8.0).ceil() * 8.0; - sheet.default_col_width = px as f32; + El { name, attrs, children, text } +} + +fn to_range_ref(r: craft_xlsx::Range) -> RangeRef { + RangeRef::new(CellRef::new(r.first.row, r.first.col), CellRef::new(r.last.row, r.last.col)) +} + +fn map_craft_error(e: craft_xlsx::CellError) -> CellError { + match e { + craft_xlsx::CellError::Null => CellError::Null, + craft_xlsx::CellError::Div0 => CellError::Div0, + craft_xlsx::CellError::Value => CellError::Value, + craft_xlsx::CellError::Ref => CellError::Ref, + craft_xlsx::CellError::Name => CellError::Name, + craft_xlsx::CellError::Num => CellError::Num, + craft_xlsx::CellError::NA => CellError::NA, + craft_xlsx::CellError::GettingData => CellError::GettingData, + craft_xlsx::CellError::Spill => CellError::Spill, + craft_xlsx::CellError::Calc => CellError::Calc, + _ => CellError::Value, } } /// Reads the sheet part `part`, with the VML shape numbers of the form controls read into the /// model (pass-through keeps the other controls). pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, crate::controls::ReadControls), IoError> { - let bytes = cx.pkg.read(part)?.ok_or_else(|| IoError::Format(format!("missing part {part}")))?; + if !cx.pkg.has(part) { + return Err(IoError::Format(format!("missing part {part}"))); + } let rels = cx.pkg.rels(part)?; let mut sheet = Sheet::new(name); let mut st = RowState::default(); - let res = xml::parse_streaming(&bytes, &["row"], &mut |row| read_row(cx, &mut sheet, &mut st, &row)); - let root = match res { - Ok(r) => r, - Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), - Err(e) => { - cx.warn(format!("sheet \"{name}\" is damaged ({e}); kept {} rows", st.rows)); - El::default() - } + let entry = CraftSheetEntry { + name: name.to_string(), + sheet_id: 0, + rel_id: String::new(), + kind: CraftSheetKind::Worksheet, + visibility: CraftVisibility::Visible, + part: Some(part.to_string()), }; - if st.dropped > 0 { - cx.warn(format!("sheet \"{name}\": {} cells or rows outside the 1,048,576 × 16,384 grid were dropped", st.dropped)); + let prev_warnings = cx.pkg.craft_mut().warnings().len(); + let mut remaining_cells = MAX_CELLS.saturating_sub(cx.cells); + let mut rows = Vec::new(); + let sheet_part = cx + .pkg + .craft_mut() + .sheet(&entry, |row| { + let n = row.cells.len() as u64; + if n > remaining_cells { + return Err(craft_xlsx::Error::TooLarge(format!("the workbook has more than {MAX_CELLS} cells"))); + } + remaining_cells -= n; + rows.push(row); + Ok(()) + }) + .map_err(|e| match e { + craft_xlsx::Error::TooLarge(m) if m.contains("XML") || m.contains("node") || m.contains("nested") => { + IoError::Format(format!("sheet \"{name}\" is damaged ({m})")) + } + other => craft_error(other), + })?; + let total_cells: u64 = rows.iter().map(|r| r.cells.len() as u64).sum(); + if sheet_part.dropped_cells > 0 && sheet_part.dropped_cells.saturating_add(total_cells) > crate::xml::MAX_XML_NODES as u64 { + cx.warn(format!("sheet \"{name}\" is damaged: more than {} cells", crate::xml::MAX_XML_NODES)); + return Ok((Sheet::new(name), Default::default())); + } + if sheet_part.merges.len() > crate::xml::MAX_XML_NODES { + cx.warn(format!("sheet \"{name}\" is damaged: more than {} merge cells", crate::xml::MAX_XML_NODES)); + return Ok((Sheet::new(name), Default::default())); + } + for row in &rows { + read_craft_row(cx, &mut sheet, &mut st, row).map_err(craft_error)?; + } + charge_cells(cx, sheet_part.dropped_cells)?; + let new_warnings: Vec = cx.pkg.craft_mut().warnings().get(prev_warnings..).unwrap_or_default().to_vec(); + for w in new_warnings { + cx.warn(w); } settle_python_spills_past_budget(&st, &mut sheet); - drop(bytes); - // Relationships by id: hyperlinks, drawings and tables each look one up. + apply_craft_sheet_part(cx, &sheet_part, &rels, name, &mut sheet)?; + let root = from_craft_el(&sheet_part.root); + let read_controls = read_form_controls(cx, &root, &rels, &mut sheet); + read_sheet_notes_and_tables(cx, &sheet_part, &rels, &mut sheet)?; + Ok((sheet, read_controls)) +} + +fn apply_craft_sheet_part(cx: &mut Ctx<'_>, sp: &CraftSheetPart, rels: &[Rel], name: &str, sheet: &mut Sheet) -> Result<(), IoError> { let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(rels.len()); - for r in &rels { - // The first of duplicate ids wins, as a linear search would find it. + for r in rels { rel_by_id.entry(r.id.as_str()).or_insert(r); } + if let Some(fmt) = &sp.features.format { + if let Some(h) = fmt.default_row_height { + let px = pt_to_px(h); + if px > 0.0 { + sheet.default_row_height = px; + } + } + if let Some(w) = fmt.default_col_width { + let px = col_width_to_px(w); + if px > 0.0 { + sheet.default_col_width = px; + } + } else if let Some(b) = fmt.base_col_width { + let px = ((f64::from(b.min(255)) * 7.0 + 5.0) / 8.0).ceil() * 8.0; + sheet.default_col_width = px as f32; + } + } + let cols_blocks = sp.root.children.iter().filter(|n| matches!(n, craft_xml::Node::El(e) if e.name == "cols")).count(); + if cols_blocks > 1 { + apply_xml_cols(cx, sp, sheet)?; + } else { + apply_craft_cols(cx, &sp.columns, sheet)?; + } + for m in &sp.merges { + if !m.is_single() { + sheet.merges.push(to_range_ref(*m)); + } + } + if let Some(v) = sp.features.views.first() { + apply_craft_view(v, sheet); + } let mut fit_to_page = false; - let mut link_budget = LinkBudget::default(); let mut cf_kept_cells = 0u64; - let mut column_assignments_left = MAX_COLUMN_ASSIGNMENTS; cx.cf_ext_ids.clear(); - for e in &root.children { - match e.name.as_str() { + for cf in &sp.features.conditional_formats { + read_cf(cx, &from_craft_el(&cf.to_el()), sheet, &mut cf_kept_cells); + } + if let Some(vals) = &sp.features.validations { + for v in &vals.items { + if let Some(val) = read_validation(&from_craft_el(&v.to_el())) { + sheet.validations.push(val); + } + } + } + for node in &sp.root.children { + let craft_xml::Node::El(child) = node else { continue }; + match child.name.as_str() { "sheetPr" => { + let e = from_craft_el(child); if let Some(t) = e.child("tabColor") { sheet.tab_color = Some(read_color(t, &cx.palette)); } @@ -232,146 +332,325 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } fit_to_page = e.child("pageSetUpPr").is_some_and(|p| p.flag("fitToPage", false)); } - "sheetViews" => read_views(e, &mut sheet), - "sheetFormatPr" => read_sheet_format(e, &mut sheet), - "cols" => read_cols(cx, e, &mut sheet, &mut column_assignments_left)?, - "mergeCells" => { - for m in e.kids("mergeCell") { - if let Some(r) = m.attr("ref").and_then(RangeRef::parse) - && !r.is_single() - { - sheet.merges.push(r); - } + "sheetProtection" => { + let e = from_craft_el(child); + if e.flag("sheet", false) { + sheet.protection = Some(SheetProtection { + password: read_password(&e, ""), + legacy_password_hash: None, + select_locked: !e.flag("selectLockedCells", false), + select_unlocked: !e.flag("selectUnlockedCells", false), + format_cells: !e.flag("formatCells", true), + format_columns: !e.flag("formatColumns", true), + format_rows: !e.flag("formatRows", true), + insert_columns: !e.flag("insertColumns", true), + insert_rows: !e.flag("insertRows", true), + delete_columns: !e.flag("deleteColumns", true), + delete_rows: !e.flag("deleteRows", true), + sort: !e.flag("sort", true), + autofilter: !e.flag("autoFilter", true), + }); } } - "conditionalFormatting" => read_cf(cx, e, &mut sheet, &mut cf_kept_cells), - "dataValidations" => { - for v in e.kids("dataValidation") { - if let Some(v) = read_validation(v) { - sheet.validations.push(v); - } - } - } - "hyperlinks" => read_hyperlinks(cx, name, e, &rel_by_id, &mut sheet, &mut link_budget), - "autoFilter" => sheet.autofilter = read_autofilter(cx, e), - "printOptions" => { - sheet.print.gridlines = e.flag("gridLines", false); - sheet.print.headings = e.flag("headings", false); - sheet.print.center_h = e.flag("horizontalCentered", false); - sheet.print.center_v = e.flag("verticalCentered", false); - } - "pageMargins" => { - let m = &mut sheet.print.margins; - for (i, k) in ["left", "right", "top", "bottom", "header", "footer"].iter().enumerate() { - if let (Some(v), Some(slot)) = (e.attr_f64(k), m.get_mut(i)) { - *slot = v.clamp(0.0, 50.0) as f32; - } - } - } - "pageSetup" => { - if e.attr("orientation") == Some("landscape") { - sheet.print.orientation = Orientation::Landscape; - } - // `downThenOver` when absent (ECMA-376's default); an unknown value reads as that too. - sheet.print.page_order = e.attr("pageOrder").and_then(PageOrder::parse).unwrap_or_default(); - // The number counts only when `useFirstPageNumber` says so; otherwise it's Automatic. - sheet.print.first_page_number = e.flag("useFirstPageNumber", false).then(|| e.attr_u32("firstPageNumber")).flatten(); - if let Some(p) = e.attr_u32("paperSize").and_then(paper_name) { - sheet.print.paper = p.to_string(); - } - if let Some(s) = e.attr_u32("scale") { - sheet.print.scale = s.clamp(10, 400) as u16; - } - if fit_to_page || root.child("sheetPr").and_then(|p| p.child("pageSetUpPr")).is_some_and(|p| p.flag("fitToPage", false)) { - let w = e.attr_u32("fitToWidth").unwrap_or(1).min(32767) as u16; - let h = e.attr_u32("fitToHeight").unwrap_or(1).min(32767) as u16; - sheet.print.fit_to = Some((w, h)); - } - } - "headerFooter" => { - let pr = &mut sheet.print; - for (tag, slot) in [ - ("oddHeader", &mut pr.header), - ("oddFooter", &mut pr.footer), - ("evenHeader", &mut pr.even_header), - ("evenFooter", &mut pr.even_footer), - ("firstHeader", &mut pr.first_header), - ("firstFooter", &mut pr.first_footer), - ] { - // Excel caps each at 255 characters; a hostile file can't make them huge. - *slot = e.child(tag).map(|h| h.text.chars().take(255).collect()).unwrap_or_default(); - } - pr.different_first = e.flag("differentFirst", false); - pr.different_odd_even = e.flag("differentOddEven", false); - pr.hf_scale_with_doc = e.flag("scaleWithDoc", true); - pr.hf_align_with_margins = e.flag("alignWithMargins", true); - } - "rowBreaks" => sheet.print.row_breaks = e.kids("brk").filter_map(|b| b.attr_u32("id")).filter(|&r| r > 0 && r < MAX_ROWS).collect(), - "colBreaks" => sheet.print.col_breaks = e.kids("brk").filter_map(|b| b.attr_u32("id")).filter(|&c| c > 0 && c < MAX_COLS).collect(), - "sheetProtection" if e.flag("sheet", false) => { - sheet.protection = Some(SheetProtection { - password: read_password(e, ""), - legacy_password_hash: None, - select_locked: !e.flag("selectLockedCells", false), - select_unlocked: !e.flag("selectUnlockedCells", false), - format_cells: !e.flag("formatCells", true), - format_columns: !e.flag("formatColumns", true), - format_rows: !e.flag("formatRows", true), - insert_columns: !e.flag("insertColumns", true), - insert_rows: !e.flag("insertRows", true), - delete_columns: !e.flag("deleteColumns", true), - delete_rows: !e.flag("deleteRows", true), - sort: !e.flag("sort", true), - autofilter: !e.flag("autoFilter", true), - }); - } - "drawing" => { - if let Some(rel) = e.attr("id").and_then(|id| rel_by_id.get(id).copied()) { - let target = rel.target.clone(); - crate::drawing::read_drawing(cx, &target, &mut sheet)?; - } - } - "tableParts" => { - for tp in e.kids("tablePart") { - if let Some(rel) = tp.attr("id").and_then(|id| rel_by_id.get(id).copied()) { - let target = rel.target.clone(); - if let Some(x) = cx.optional_xml(&target)? - && let Some(mut t) = read_table(cx, &x) - { - t.id = cx.next_object_id(); - sheet.tables.push(t); - } - } - } - } - "extLst" => read_ext(cx, e, &mut sheet, &mut cf_kept_cells), - "protectedRanges" => read_protected_ranges(e, &mut sheet), + "protectedRanges" => read_protected_ranges(&from_craft_el(child), sheet), + "autoFilter" => sheet.autofilter = read_autofilter(cx, &from_craft_el(child)), + "extLst" => read_ext(cx, &from_craft_el(child), sheet, &mut cf_kept_cells), _ => {} } } - let read_controls = read_form_controls(cx, &root, &rels, &mut sheet); - // Comments are related to the sheet without an element in it. - for rel in rels.iter().filter(|r| r.kind == "comments") { - if let Some(x) = cx.optional_xml(&rel.target)? { - read_comments(&x, &mut sheet); + let mut link_budget = LinkBudget::default(); + let hyperlink_blocks = sp.root.children.iter().filter(|n| matches!(n, craft_xml::Node::El(e) if e.name == "hyperlinks")).count(); + if hyperlink_blocks > 1 { + for node in &sp.root.children { + if let craft_xml::Node::El(hl) = node + && hl.name == "hyperlinks" + { + let hl_el = from_craft_el(hl); + for h in hl_el.kids("hyperlink") { + let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue }; + let raw = RawHyperlink { range, rel_id: h.attr("id"), location: h.attr("location"), tooltip: h.attr("tooltip") }; + if !push_hyperlink(cx, name, raw, &rel_by_id, sheet, &mut link_budget) { + break; + } + } + } } + } else { + read_craft_hyperlinks(cx, name, &sp.features.hyperlinks, &rel_by_id, sheet, &mut link_budget); + } + apply_craft_print(&sp.features.print, fit_to_page, sheet); + if let Some(id) = &sp.features.drawing + && let Some(rel) = rel_by_id.get(id.as_str()).copied() + { + let target = rel.target.clone(); + crate::drawing::read_drawing(cx, &target, sheet)?; + } + Ok(()) +} + +fn read_sheet_notes_and_tables(cx: &mut Ctx<'_>, sp: &CraftSheetPart, rels: &[Rel], sheet: &mut Sheet) -> Result<(), IoError> { + let tables = cx.pkg.craft_mut().tables(sp).map_err(craft_error)?; + for (_, t) in tables { + let mut model = parts::from_craft_table(cx, &t); + model.id = cx.next_object_id(); + sheet.tables.push(model); + } + if let Some(comments) = cx.pkg.craft_mut().comments(sp).map_err(craft_error)? { + parts::apply_craft_comments(&comments, sheet); } for rel in rels.iter().filter(|r| r.kind == "threadedComment") { if let Some(x) = cx.optional_xml(&rel.target)? { - read_threaded(cx, &x, &mut sheet); + read_threaded(cx, &x, sheet); } } - // Which notes are displayed (``) and where their boxes sit live in the VML shapes. - // Best effort: the VML is only read for those, so a part that doesn't parse is skipped without - // a warning. if !sheet.comments.is_empty() { - for rel in rels.iter().filter(|r| r.kind == "vmlDrawing") { - if let Ok(Some(x)) = cx.pkg.read_xml(&rel.target) { - read_note_shapes(&x, &mut sheet, 0); + match cx.pkg.craft_mut().note_shapes(sp) { + Ok(shapes) => parts::apply_craft_note_shapes(&shapes, sheet), + Err(e) => cx.warn(format!("sheet \"{}\": note drawing could not be read ({e})", sheet.name)), + } + } + Ok(()) +} + +struct RawCol { + min: u32, + max: u32, + width: Option, + custom_width: bool, + hidden: bool, + outline_level: u8, + collapsed: bool, + style: Option, +} + +fn apply_col_entry(cx: &Ctx<'_>, c: RawCol, remaining: &mut u64, sheet: &mut Sheet) -> Result<(), IoError> { + let min = c.min; + let max = c.max.min(MAX_COLS); + if min == 0 || min > MAX_COLS || max < min { + return Ok(()); + } + let mut info = LineInfo::default(); + if let Some(w) = c.width { + let px = col_width_to_px(w); + if c.custom_width || px != sheet.default_col_width { + info.size = Some(px); + } + } + info.hidden = c.hidden; + info.outline = c.outline_level.min(7); + info.collapsed = c.collapsed; + if let Some(s) = c.style { + let id = cx.style(Some(s)); + if id != gridcraft_model::StyleId::DEFAULT { + info.style = Some(id); + } + } + if info == LineInfo::default() { + return Ok(()); + } + *remaining = remaining + .checked_sub(u64::from(max - min + 1)) + .ok_or_else(|| IoError::TooLarge(format!("sheet \"{}\": more than {MAX_COLUMN_ASSIGNMENTS} expanded column assignments", sheet.name)))?; + for col in (min - 1)..max { + sheet.cols.insert(col, info); + } + Ok(()) +} + +fn apply_craft_cols(cx: &Ctx<'_>, cols: &[craft_xlsx::Column], sheet: &mut Sheet) -> Result<(), IoError> { + let mut remaining = MAX_COLUMN_ASSIGNMENTS; + for c in cols { + let raw = RawCol { + min: c.first + 1, + max: c.last + 1, + width: c.width, + custom_width: c.custom_width, + hidden: c.hidden, + outline_level: c.outline_level, + collapsed: c.collapsed, + style: c.style, + }; + apply_col_entry(cx, raw, &mut remaining, sheet)?; + } + Ok(()) +} + +fn apply_xml_cols(cx: &Ctx<'_>, sp: &CraftSheetPart, sheet: &mut Sheet) -> Result<(), IoError> { + let mut remaining = MAX_COLUMN_ASSIGNMENTS; + for node in &sp.root.children { + if let craft_xml::Node::El(cols_el) = node + && cols_el.name == "cols" + { + let cols = from_craft_el(cols_el); + for c in cols.kids("col") { + let raw = RawCol { + min: c.attr_u32("min").unwrap_or(0), + max: c.attr_u32("max").unwrap_or(0), + width: c.attr_f64("width"), + custom_width: c.flag("customWidth", false), + hidden: c.flag("hidden", false), + outline_level: c.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8, + collapsed: c.flag("collapsed", false), + style: c.attr_u32("style"), + }; + apply_col_entry(cx, raw, &mut remaining, sheet)?; } } } - Ok((sheet, read_controls)) + Ok(()) +} + +fn apply_craft_view(v: &craft_xlsx::SheetView, sheet: &mut Sheet) { + sheet.show_gridlines = v.show_grid_lines.unwrap_or(true); + sheet.show_headings = v.show_row_col_headers.unwrap_or(true); + sheet.show_formulas = v.show_formulas.unwrap_or(false); + sheet.show_zeros = v.show_zeros.unwrap_or(true); + sheet.show_outline_symbols = v.show_outline_symbols.unwrap_or(true); + sheet.right_to_left = v.right_to_left.unwrap_or(false); + sheet.view = v.view.as_deref().and_then(gridcraft_model::SheetViewMode::parse).unwrap_or_default(); + if let Some(z) = v.zoom_scale { + sheet.zoom = z.clamp(10, 400) as u16; + } + if let Some(c) = v.top_left_cell.as_deref().and_then(CellRef::parse) { + sheet.view_top_left = c; + } + let mut active_pane = None; + if let Some(p) = &v.pane { + if matches!(p.state.as_deref(), Some("frozen" | "frozenSplit")) { + let cols = p.x_split.unwrap_or(0.0).clamp(0.0, (MAX_COLS - 1) as f64) as u32; + let rows = p.y_split.unwrap_or(0.0).clamp(0.0, (MAX_ROWS - 1) as f64) as u32; + if rows > 0 || cols > 0 { + sheet.freeze = Some((rows, cols)); + if let Some(c) = p.top_left_cell.as_deref().and_then(CellRef::parse) { + sheet.view_top_left = c; + } + } + } + active_pane = p.active_pane.as_deref(); + } + let sel = v.selections.iter().find(|s| s.pane.as_deref() == active_pane).or_else(|| v.selections.last()); + if let Some(c) = sel.and_then(|s| s.active_cell.as_deref()).and_then(CellRef::parse) { + sheet.view_active = c; + } +} + +fn apply_craft_print(print: &craft_xlsx::Print, fit_to_page: bool, sheet: &mut Sheet) { + if let Some(o) = &print.options { + sheet.print.gridlines = o.grid_lines.unwrap_or(false); + sheet.print.headings = o.headings.unwrap_or(false); + sheet.print.center_h = o.horizontal_centered.unwrap_or(false); + sheet.print.center_v = o.vertical_centered.unwrap_or(false); + } + if let Some(pm) = &print.margins { + for (i, v) in [pm.left, pm.right, pm.top, pm.bottom, pm.header, pm.footer].into_iter().enumerate() { + if let (Some(v), Some(slot)) = (v, sheet.print.margins.get_mut(i)) { + *slot = v.clamp(0.0, 50.0) as f32; + } + } + } + if let Some(ps) = &print.setup { + if ps.orientation.as_deref() == Some("landscape") { + sheet.print.orientation = Orientation::Landscape; + } + sheet.print.page_order = ps.page_order.as_deref().and_then(PageOrder::parse).unwrap_or_default(); + sheet.print.first_page_number = if ps.use_first_page_number.unwrap_or(false) { ps.first_page_number } else { None }; + if let Some(p) = ps.paper_size.and_then(paper_name) { + sheet.print.paper = p.to_string(); + } + if let Some(s) = ps.scale { + sheet.print.scale = s.clamp(10, 400) as u16; + } + if fit_to_page { + let w = ps.fit_to_width.unwrap_or(1).min(32767) as u16; + let h = ps.fit_to_height.unwrap_or(1).min(32767) as u16; + sheet.print.fit_to = Some((w, h)); + } + } + if let Some(hf) = &print.header_footer { + let pr = &mut sheet.print; + for (src, slot) in [ + (&hf.odd_header, &mut pr.header), + (&hf.odd_footer, &mut pr.footer), + (&hf.even_header, &mut pr.even_header), + (&hf.even_footer, &mut pr.even_footer), + (&hf.first_header, &mut pr.first_header), + (&hf.first_footer, &mut pr.first_footer), + ] { + *slot = src.as_deref().unwrap_or("").chars().take(255).collect(); + } + pr.different_first = hf.different_first.unwrap_or(false); + pr.different_odd_even = hf.different_odd_even.unwrap_or(false); + pr.hf_scale_with_doc = hf.scale_with_doc.unwrap_or(true); + pr.hf_align_with_margins = hf.align_with_margins.unwrap_or(true); + } + sheet.print.row_breaks = print.row_breaks.iter().filter_map(|b| b.id).filter(|&r| r > 0 && r < MAX_ROWS).collect(); + sheet.print.col_breaks = print.col_breaks.iter().filter_map(|b| b.id).filter(|&c| c > 0 && c < MAX_COLS).collect(); +} + +struct RawHyperlink<'a> { + range: RangeRef, + rel_id: Option<&'a str>, + location: Option<&'a str>, + tooltip: Option<&'a str>, +} + +fn push_hyperlink(cx: &mut Ctx<'_>, name: &str, h: RawHyperlink<'_>, rels: &HashMap<&str, &Rel>, sheet: &mut Sheet, budget: &mut LinkBudget) -> bool { + let rel_target = h.rel_id.and_then(|id| rels.get(id)).map(|r| r.target.as_str()).unwrap_or(""); + let location = h.location.filter(|l| !l.is_empty()); + if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET { + cx.warn(format!("sheet \"{name}\": hyperlinks longer than {MAX_HYPERLINK_TARGET} characters were dropped")); + return true; + } + let mut target = rel_target.to_string(); + let external = !target.is_empty(); + if let Some(loc) = location { + if target.is_empty() { + target = loc.trim_start_matches('#').to_string(); + } else { + target = format!("{target}#{loc}"); + } + } + if target.is_empty() { + return true; + } + let tooltip = h.tooltip.map(|t| truncate_chars(t, MAX_TOOLTIP_CHARS)); + let link_bytes = (target.len() + tooltip.as_ref().map_or(0, String::len)) as u64; + let link = Hyperlink { target, tooltip, external }; + for c in h.range.iter() { + if budget.cells >= MAX_HYPERLINK_CELLS { + cx.warn(format!("sheet \"{name}\": hyperlinks past the first {MAX_HYPERLINK_CELLS} cells were dropped")); + return false; + } + if budget.bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES { + cx.warn(format!("sheet \"{name}\": hyperlink targets past {MAX_HYPERLINK_BYTES} bytes were dropped")); + return false; + } + budget.cells += 1; + budget.bytes += link_bytes; + sheet.hyperlinks.insert(c, link.clone()); + } + true +} + +fn read_craft_hyperlinks( + cx: &mut Ctx<'_>, + name: &str, + links: &[craft_xlsx::Hyperlink], + rels: &HashMap<&str, &Rel>, + sheet: &mut Sheet, + budget: &mut LinkBudget, +) { + for h in links { + let raw = RawHyperlink { + range: to_range_ref(h.range), + rel_id: h.rel_id.as_deref(), + location: h.location.as_deref(), + tooltip: h.tooltip.as_deref(), + }; + if !push_hyperlink(cx, name, raw, rels, sheet, budget) { + return; + } + } } /// Buttons, scroll bars and spin buttons: the `` list (also inside @@ -427,82 +706,6 @@ fn read_protected_ranges(e: &El, sheet: &mut Sheet) { } } -fn read_views(e: &El, sheet: &mut Sheet) { - let Some(v) = e.child("sheetView") else { return }; - sheet.show_gridlines = v.flag("showGridLines", true); - sheet.show_headings = v.flag("showRowColHeaders", true); - sheet.show_formulas = v.flag("showFormulas", false); - sheet.show_zeros = v.flag("showZeros", true); - sheet.show_outline_symbols = v.flag("showOutlineSymbols", true); - sheet.right_to_left = v.flag("rightToLeft", false); - sheet.view = v.attr("view").and_then(gridcraft_model::SheetViewMode::parse).unwrap_or_default(); - if let Some(z) = v.attr_u32("zoomScale") { - sheet.zoom = z.clamp(10, 400) as u16; - } - if let Some(c) = v.attr("topLeftCell").and_then(CellRef::parse) { - sheet.view_top_left = c; - } - let mut active_pane = None; - if let Some(p) = v.child("pane") { - if matches!(p.attr("state"), Some("frozen") | Some("frozenSplit")) { - let cols = p.attr_f64("xSplit").unwrap_or(0.0).clamp(0.0, (MAX_COLS - 1) as f64) as u32; - let rows = p.attr_f64("ySplit").unwrap_or(0.0).clamp(0.0, (MAX_ROWS - 1) as f64) as u32; - if rows > 0 || cols > 0 { - sheet.freeze = Some((rows, cols)); - // With frozen panes the scroll position is the scrolling pane's first cell. - if let Some(c) = p.attr("topLeftCell").and_then(CellRef::parse) { - sheet.view_top_left = c; - } - } - } - active_pane = p.attr("activePane"); - } - let sel = v.kids("selection").find(|s| s.attr("pane") == active_pane).or_else(|| v.kids("selection").last()); - if let Some(c) = sel.and_then(|s| s.attr("activeCell")).and_then(CellRef::parse) { - sheet.view_active = c; - } -} - -fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Result<(), IoError> { - for c in e.kids("col") { - let (Some(min), Some(max)) = (c.attr_u32("min"), c.attr_u32("max")) else { continue }; - if min == 0 || min > MAX_COLS || max < min { - continue; - } - let max = max.min(MAX_COLS); - let mut info = LineInfo::default(); - // A width without `customWidth` that equals the default is just the default. - if let Some(w) = c.attr_f64("width") { - let px = col_width_to_px(w); - if c.flag("customWidth", false) || px != sheet.default_col_width { - info.size = Some(px); - } - } - info.hidden = c.flag("hidden", false); - info.outline = c.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8; - info.collapsed = c.flag("collapsed", false); - if let Some(s) = c.attr_u32("style") { - let id = cx.style(Some(s)); - if id != gridcraft_model::StyleId::DEFAULT { - info.style = Some(id); - } - } - // A custom width equal to the default still pins the column (Standard Width leaves it alone). - if info == LineInfo::default() { - continue; - } - // Overlapping declarations repeat work even when the final map stays small. - // Charge the clipped span before expansion, sharing the budget across blocks. - *remaining = remaining - .checked_sub(u64::from(max - min + 1)) - .ok_or_else(|| IoError::TooLarge(format!("sheet \"{}\": more than {MAX_COLUMN_ASSIGNMENTS} expanded column assignments", sheet.name)))?; - for col in (min - 1)..max { - sheet.cols.insert(col, info); - } - } - Ok(()) -} - /// Charges `n` cell elements against the workbook's [`MAX_CELLS`]. fn charge_cells(cx: &mut Ctx<'_>, n: u64) -> Result<(), IoError> { cx.cells = cx.cells.saturating_add(n); @@ -512,133 +715,82 @@ fn charge_cells(cx: &mut Ctx<'_>, n: u64) -> Result<(), IoError> { Ok(()) } -/// One ``. Every `` in it counts against [`MAX_CELLS`], also in a row that is dropped -/// for a bad row number: one worksheet part read for many sheets can't parse cells uncounted. -fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) -> Result<(), IoError> { - st.rows += 1; - let r = match row.attr_u32("r") { - Some(r) if r >= 1 => r - 1, - Some(_) => { - st.dropped += 1; - return charge_cells(cx, row.kids("c").count() as u64); - } - None => st.next_row, - }; - if r >= MAX_ROWS { - st.dropped += 1; - return charge_cells(cx, row.kids("c").count() as u64); - } - st.next_row = r + 1; +fn read_craft_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &CraftRow) -> Result<(), craft_xlsx::Error> { + let r = row.index; let mut info = LineInfo::default(); - if let Some(ht) = row.attr_f64("ht") { - info.custom = row.flag("customHeight", false); - // Automatic heights equal to the default are noise. + if let Some(ht) = row.height { + info.custom = row.custom_height; if info.custom || (pt_to_px(ht) - sheet.default_row_height).abs() > 0.5 { info.size = Some(pt_to_px(ht)); } } - info.hidden = row.flag("hidden", false); - info.outline = row.attr_u32("outlineLevel").unwrap_or(0).min(7) as u8; - info.collapsed = row.flag("collapsed", false); - if row.flag("customFormat", false) - && let Some(s) = row.attr_u32("s") - { + info.hidden = row.hidden; + info.outline = row.outline_level.min(7); + info.collapsed = row.collapsed; + if let Some(s) = row.style { info.style = Some(cx.style(Some(s))); } if info != LineInfo::default() { sheet.rows.insert(r, info); } - let mut next_col = 0u32; - for c in row.kids("c") { - charge_cells(cx, 1)?; - let pos = match c.attr("r") { - Some(a) => match CellRef::parse(a.trim()) { - Some(p) => p, - None => { - st.dropped += 1; - continue; - } - }, - None => CellRef::new(r, next_col), - }; - if pos.col >= MAX_COLS || pos.row >= MAX_ROWS { - st.dropped += 1; - continue; - } - next_col = pos.col + 1; - read_cell(cx, sheet, st, c, pos); + for c in &row.cells { + charge_cells(cx, 1).map_err(|e| craft_xlsx::Error::TooLarge(e.to_string()))?; + let pos = CellRef::new(c.at.row, c.at.col); + read_craft_cell(cx, sheet, st, c, pos); } Ok(()) } -fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos: CellRef) { - let style = cx.style(c.attr_u32("s")); - let v = c.child("v").map(|v| v.text.as_str()); - let value = match c.attr("t").unwrap_or("n") { - "s" => match v.and_then(|v| v.trim().parse::().ok()) { - Some(i) => match cx.sst.get(i) { - Some(s) => Value::Text(s.clone()), - None => { - cx.warn("some cells refer to missing shared strings"); - Value::Empty - } - }, - None => Value::Empty, - }, - "str" => v.map(|v| Value::text(xml::decode_xstring(v))).unwrap_or(Value::Empty), - "inlineStr" => { - c.child("is").map(|is| Value::text(xml::rich_text(is))).or_else(|| v.map(|v| Value::text(xml::decode_xstring(v)))).unwrap_or(Value::Empty) - } - "b" => v.map(|v| Value::Bool(matches!(v.trim(), "1" | "true" | "TRUE"))).unwrap_or(Value::Empty), - "e" => v.map(|v| Value::Error(CellError::parse(v.trim()).unwrap_or(CellError::Value))).unwrap_or(Value::Empty), - "d" => match v.and_then(|v| parse_iso_datetime(v.trim(), cx.date_system)) { - Some(n) => Value::number(n), +fn read_craft_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &craft_xlsx::Cell, pos: CellRef) { + let style = cx.style((c.style != 0).then_some(c.style)); + let value = match &c.value { + CraftValue::Empty => Value::Empty, + CraftValue::Shared(i) => match cx.sst.get(*i as usize) { + Some(s) => Value::Text(s.clone()), None => { - if let Some(v) = v - && !v.trim().is_empty() - { - cx.warn("some date cells could not be read"); - } + cx.warn("some cells refer to missing shared strings"); Value::Empty } }, - _ => match v.map(str::trim).filter(|v| !v.is_empty()) { - Some(t) => match t.parse::() { - Ok(n) if n.is_finite() => Value::Number(if n == 0.0 { 0.0 } else { n }), - _ => { - cx.warn("some numeric cells could not be read"); - Value::Empty - } - }, - None => Value::Empty, + CraftValue::Text(t) => Value::Text(t.as_ref().into()), + CraftValue::Inline(s) => Value::Text(s.text.as_ref().into()), + CraftValue::Bool(b) => Value::Bool(*b), + CraftValue::Error(e) => Value::Error(map_craft_error(*e)), + CraftValue::Date(d) => match parse_iso_datetime(d, cx.date_system) { + Some(n) => Value::number(n), + None => { + cx.warn("some date cells could not be read"); + Value::Empty + } }, + CraftValue::Number(n) => Value::Number(*n), + CraftValue::Invalid(_) => { + cx.warn("some numeric cells could not be read"); + Value::Empty + } }; - let picture = c.attr("vm").and_then(|vm| { - if vm == "0" { + let picture = c.value_metadata.and_then(|vm| { + if vm == 0 { return None; } - let picture = vm.parse::().ok().and_then(|n| n.checked_sub(1)).and_then(|n| cx.cell_pictures.get(n)).cloned().flatten(); + let picture = (vm as usize).checked_sub(1).and_then(|n| cx.cell_pictures.get(n)).cloned().flatten(); if picture.is_none() { cx.warn("some cells have unsupported or missing value metadata; kept their scalar fallback (cell pictures may be missing)"); } picture }); if let Some(picture) = picture { - if c.child("f").is_some() { + if c.formula.is_some() { cx.warn("formula-generated cell pictures were imported as static pictures; their formulas were not retained"); } sheet.set_picture(pos, picture); sheet.set_style(pos, style); return; } - let dynamic = c.attr("cm").is_some(); + let dynamic = c.cell_metadata.is_some(); st.shared_copy_refused = false; - let formula = c.child("f").and_then(|f| read_formula(cx, st, f, pos, dynamic)); - // A `PY(index,0|1)` formula is a Python cell whose code is a script of the Python part. The - // older `PY("…",0|1)` form is read from the formula's own text: the formula parser would fold - // line breaks in the code. A formula naming a script the part lacks keeps only its cached - // values, its own and its spill's, as plain values. - let py = match (&formula, c.child("f")) { + let formula = c.formula.as_ref().and_then(|f| read_craft_formula(cx, st, f, pos, dynamic)); + let py = match (&formula, &c.formula) { (Some(fm), Some(f)) => crate::python_part::cell_code(&mut cx.python, fm, &f.text), _ => crate::python_part::PyFormula::Not, }; @@ -653,15 +805,12 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos if py.is_some() { record_python_spill(st, sheet, pos); } - // A formula without dynamic-array metadata is a legacy formula, unless entered as a - // Ctrl+Shift+Enter array or unwrapped from Google Sheets' export (#2871). if formula.as_ref().is_some_and(|f| !f.dynamic && f.array.is_none() && f.expr_arc().is_some()) { cx.legacy_formulas.push(pos); } let spilled_from = if formula.is_none() && py.is_none() && !st.shared_copy_refused { dynamic_range(st, pos) } else { None }; let python_anchor = spilled_from.is_some_and(|r| sheet.cells.get(r.start).is_some_and(|a| a.py.is_some())); let value = match spilled_from { - // A Python cell's spilled values are kept: they are its result until it runs again. Some(r) if python_anchor && r.count() <= gridcraft_model::python::MAX_RESULT_CELLS as u64 => { if !value.is_empty() { sheet.spill.insert(pos, value); @@ -669,16 +818,10 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos sheet.spill_ranges.insert(r.start, r); Value::Empty } - // A Python cell's range larger than a result may be is a crafted file's: it is no spill, - // and its cells keep the values the file shows as plain values, as when the cell keeps - // only its own value. Some(_) if python_anchor => value, - // A formula's spilled values are dropped: recalculation fills them again. Some(_) => Value::Empty, None => value, }; - // A dynamic array keeps the area it was saved spilling over (`ref`): when two arrays want the - // same cells, recalculating gives them to this one again, as before saving. if dynamic && formula.as_ref().is_some_and(|f| f.array.is_none()) && let Some(r) = st.dynamic.last().filter(|r| r.start == pos) @@ -688,16 +831,21 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style, py }); } -fn read_formula(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, dynamic: bool) -> Option { - // Keep the file's dynamic-array mark (and treat Google Sheets unwrapped formulas as dynamic), - // so saving never turns the formula into a legacy one. +fn read_craft_formula(cx: &mut Ctx<'_>, st: &mut RowState, f: &CraftFormula, pos: CellRef, dynamic: bool) -> Option { let mut unwrapped = false; - let fm = read_formula_text(cx, st, f, pos, dynamic, &mut unwrapped)?; + let fm = read_craft_formula_text(cx, st, f, pos, dynamic, &mut unwrapped)?; let dynamic = dynamic || unwrapped; Some(Formula { dynamic, ..fm }) } -fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, dynamic: bool, unwrapped: &mut bool) -> Option { +fn read_craft_formula_text( + cx: &mut Ctx<'_>, + st: &mut RowState, + f: &CraftFormula, + pos: CellRef, + dynamic: bool, + unwrapped: &mut bool, +) -> Option { let mut model = from_file(f.text.trim()); if let Some(known) = cx.known_function && let Some(u) = unwrap_google_sheets(&model, known) @@ -706,9 +854,9 @@ fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, *unwrapped = true; } let text = model.as_str(); - match f.attr("t").unwrap_or("normal") { - "shared" => { - let si = f.attr_u32("si")?; + match f.kind { + CraftFormulaKind::Shared => { + let si = f.shared_index?; if !text.is_empty() { let expr = gridcraft_formula::parse(text).ok(); let cost = shared_cost(text, expr.as_ref()); @@ -719,8 +867,6 @@ fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, cx.warn("a shared formula refers to a missing master cell; kept the cached value"); return None; }; - // The parser's own test: bytes first (cheap), then characters, so a multibyte - // master that failed to parse for another reason gets no false length warning. if sh.expr.is_none() && sh.text.len() > gridcraft_formula::MAX_FORMULA_LEN && sh.text.chars().count() > gridcraft_formula::MAX_FORMULA_LEN @@ -748,12 +894,12 @@ fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, }) } } - "array" => { + CraftFormulaKind::Array => { if text.is_empty() { return None; } let mut fm = Formula::new(text); - let range = f.attr("ref").and_then(RangeRef::parse).unwrap_or(RangeRef::cell(pos)); + let range = f.range.map(to_range_ref).unwrap_or(RangeRef::cell(pos)); if !range.is_single() { push_dynamic(st, range); } @@ -762,11 +908,11 @@ fn read_formula_text(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, } Some(fm) } - "dataTable" => { + CraftFormulaKind::DataTable => { cx.warn("what-if data tables are not supported; kept their values"); None } - _ => { + CraftFormulaKind::Normal => { if text.is_empty() { None } else { diff --git a/crates/xlsx/src/sheet_read/parts.rs b/crates/xlsx/src/sheet_read/parts.rs index a01bb5481..2c5f6d1cd 100644 --- a/crates/xlsx/src/sheet_read/parts.rs +++ b/crates/xlsx/src/sheet_read/parts.rs @@ -1,49 +1,104 @@ use super::{ - AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, Hyperlink, LinkBudget, MAX_COLS, MAX_HYPERLINK_BYTES, MAX_HYPERLINK_CELLS, - MAX_HYPERLINK_TARGET, MAX_ROWS, MAX_TOOLTIP_CHARS, NoteBox, NoteCorner, RangeRef, Rel, Sheet, Table, TableColumn, TotalsFn, XmlColumnPr, - from_file, truncate_chars, xml, + AutoFilter, CellRef, Comment, Ctx, El, FilterCriterion, HashMap, MAX_COLS, MAX_ROWS, NoteBox, NoteCorner, RangeRef, Sheet, Table, TableColumn, + TotalsFn, XmlColumnPr, from_file, xml, }; /// `rels` maps relationship ids to relationships (the first of duplicate ids). `budget` counts the /// cells and bytes this sheet's hyperlinks have copied so far, across `` blocks. -pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &HashMap<&str, &Rel>, sheet: &mut Sheet, budget: &mut LinkBudget) { - for h in e.kids("hyperlink") { - let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue }; - let rel_target = h.attr("id").and_then(|id| rels.get(id)).map(|r| r.target.as_str()).unwrap_or(""); - let location = h.attr("location").filter(|l| !l.is_empty()); - // Each covered cell gets its own copy of the link: refuse oversized targets before copying. - if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET { - cx.warn(format!("sheet \"{name}\": hyperlinks longer than {MAX_HYPERLINK_TARGET} characters were dropped")); - continue; - } - let mut target = rel_target.to_string(); - // A relationship is a file or web page; a bare `location` is a place in this workbook. - let external = !target.is_empty(); - if let Some(loc) = location { - if target.is_empty() { - target = loc.trim_start_matches('#').to_string(); - } else { - target = format!("{target}#{loc}"); +pub(super) fn from_craft_table(cx: &mut Ctx<'_>, t: &craft_xlsx::Table) -> Table { + let columns = t + .columns + .iter() + .map(|c| { + let totals = match c.totals_row_function.as_deref().unwrap_or("none") { + "average" => TotalsFn::Average, + "count" => TotalsFn::Count, + "countNums" => TotalsFn::CountNums, + "max" => TotalsFn::Max, + "min" => TotalsFn::Min, + "sum" => TotalsFn::Sum, + "stdDev" => TotalsFn::StdDev, + "var" => TotalsFn::Var, + "custom" => TotalsFn::Custom, + _ => TotalsFn::None, + }; + let totals_label = + if totals == TotalsFn::Custom { c.totals_row_formula.as_ref().map(|(f, _)| from_file(f.trim())) } else { c.totals_row_label.clone() }; + let xml = c.other.iter().find(|e| e.name == "xmlColumnPr").and_then(|x| { + Some(XmlColumnPr { + map_id: x.attr_u32("mapId")?, + xpath: x.attr("xpath")?.to_string(), + data_type: x.attr("xmlDataType").unwrap_or("string").to_string(), + denormalized: x.flag("denormalized", false), + }) + }); + TableColumn { + name: xml::decode_xstring(c.name.as_deref().unwrap_or("")), + totals, + totals_label, + formula: c.calculated_formula.as_ref().map(|(f, _)| from_file(f.trim())), + unique_name: c.unique_name.clone(), + xml, } + }) + .collect(); + let xml_table = t.table_type.as_deref() == Some("xml"); + let si = t.style.as_ref(); + let filter = t.auto_filter.as_ref().and_then(|af| read_autofilter(cx, &super::from_craft_el(af))).map(|af| af.criteria).unwrap_or_default(); + Table { + id: t.id.unwrap_or(0), + name: t.display_name.as_deref().or(t.name.as_deref()).unwrap_or("Table").to_string(), + range: super::to_range_ref(t.range), + header_row: t.header_row_count.unwrap_or(1) > 0, + totals_row: t.totals_row_count.unwrap_or(0) > 0, + columns, + style: si.and_then(|s| s.name.as_deref()).unwrap_or("").to_string(), + banded_rows: si.is_some_and(|s| s.show_row_stripes.unwrap_or(false)), + banded_cols: si.is_some_and(|s| s.show_column_stripes.unwrap_or(false)), + first_col: si.is_some_and(|s| s.show_first_column.unwrap_or(false)), + last_col: si.is_some_and(|s| s.show_last_column.unwrap_or(false)), + filter_button: t.auto_filter.is_some(), + filter, + table_type: xml_table.then(|| "xml".to_string()), + connection_id: t.connection_id.filter(|_| xml_table), + } +} + +pub(super) fn apply_craft_comments(comments: &craft_xlsx::Comments, sheet: &mut Sheet) { + for c in &comments.comments { + let cell = CellRef::new(c.at.row, c.at.col); + let author = comments.author(c).unwrap_or("").to_string(); + let mut text = c.text.text.to_string(); + if !author.is_empty() + && let Some(rest) = text.strip_prefix(&format!("{author}:")) + { + text = rest.strip_prefix('\n').unwrap_or(rest).to_string(); } - if target.is_empty() { - continue; + sheet + .comments + .insert(cell, Comment { author, text, replies: vec![], threaded: false, resolved: false, visible: false, dates: vec![], note_box: None }); + } +} + +pub(super) fn apply_craft_note_shapes(shapes: &[craft_xlsx::NoteShape], sheet: &mut Sheet) { + for s in shapes { + let cell = CellRef::new(s.at.row, s.at.col); + let Some(c) = sheet.comments.get_mut(&cell) else { continue }; + if s.visible && !c.threaded { + c.visible = true; } - let tooltip = h.attr("tooltip").map(|t| truncate_chars(t, MAX_TOOLTIP_CHARS)); - let link_bytes = (target.len() + tooltip.as_ref().map_or(0, String::len)) as u64; - let link = Hyperlink { target, tooltip, external }; - for c in range.iter() { - if budget.cells >= MAX_HYPERLINK_CELLS { - cx.warn(format!("sheet \"{name}\": hyperlinks past the first {MAX_HYPERLINK_CELLS} cells were dropped")); - return; - } - if budget.bytes.saturating_add(link_bytes) > MAX_HYPERLINK_BYTES { - cx.warn(format!("sheet \"{name}\": hyperlink targets past {MAX_HYPERLINK_BYTES} bytes were dropped")); - return; - } - budget.cells += 1; - budget.bytes += link_bytes; - sheet.hyperlinks.insert(c, link.clone()); + if let Some([c1, dx1, r1, dy1, c2, dx2, r2, dy2]) = s.anchor + && c1.max(c2) < MAX_COLS + && r1.max(r2) < MAX_ROWS + { + let corner = |col: u32, col_px: u32, row: u32, row_px: u32| NoteCorner { + col: i64::from(col) - i64::from(cell.col), + col_px, + row: i64::from(row) - i64::from(cell.row), + row_px, + }; + let nb = NoteBox { from: corner(c1, dx1, r1, dy1), to: corner(c2, dx2, r2, dy2), size_pt: s.size_pt }; + c.note_box = (nb != crate::sheet_write::DEFAULT_NOTE_BOX).then_some(nb); } } } @@ -102,145 +157,6 @@ pub fn read_autofilter(cx: &mut Ctx<'_>, e: &El) -> Option { Some(AutoFilter { range, criteria }) } -pub fn read_table(cx: &mut Ctx<'_>, x: &El) -> Option { - let range = x.attr("ref").and_then(RangeRef::parse)?; - let name = x.attr("displayName").or_else(|| x.attr("name")).unwrap_or("Table").to_string(); - let header_row = x.attr_u32("headerRowCount").unwrap_or(1) > 0; - let totals_row = x.attr_u32("totalsRowCount").unwrap_or(0) > 0; - let columns = x - .child("tableColumns") - .map(|tc| { - tc.kids("tableColumn") - .map(|c| { - let totals = match c.attr("totalsRowFunction").unwrap_or("none") { - "average" => TotalsFn::Average, - "count" => TotalsFn::Count, - "countNums" => TotalsFn::CountNums, - "max" => TotalsFn::Max, - "min" => TotalsFn::Min, - "sum" => TotalsFn::Sum, - "stdDev" => TotalsFn::StdDev, - "var" => TotalsFn::Var, - "custom" => TotalsFn::Custom, - _ => TotalsFn::None, - }; - let totals_label = if totals == TotalsFn::Custom { - c.child("totalsRowFormula").map(|f| from_file(f.text.trim())) - } else { - c.attr("totalsRowLabel").map(str::to_string) - }; - TableColumn { - name: xml::decode_xstring(c.attr("name").unwrap_or("")), - totals, - totals_label, - formula: c.child("calculatedColumnFormula").map(|f| from_file(f.text.trim())), - unique_name: c.attr("uniqueName").map(str::to_string), - xml: c.child("xmlColumnPr").and_then(|x| { - Some(XmlColumnPr { - map_id: x.attr_u32("mapId")?, - xpath: x.attr("xpath")?.to_string(), - data_type: x.attr("xmlDataType").unwrap_or("string").to_string(), - denormalized: x.flag("denormalized", false), - }) - }), - } - }) - .collect() - }) - .unwrap_or_default(); - let si = x.child("tableStyleInfo"); - // Only XML tables are kept as such: a query table's definition hangs off the table part, which - // is rewritten, so it would lose it. - let xml_table = x.attr("tableType") == Some("xml"); - Some(Table { - id: x.attr_u32("id").unwrap_or(0), - name, - range, - header_row, - totals_row, - columns, - style: si.and_then(|s| s.attr("name")).unwrap_or("").to_string(), - banded_rows: si.is_some_and(|s| s.flag("showRowStripes", false)), - banded_cols: si.is_some_and(|s| s.flag("showColumnStripes", false)), - first_col: si.is_some_and(|s| s.flag("showFirstColumn", false)), - last_col: si.is_some_and(|s| s.flag("showLastColumn", false)), - filter_button: x.child("autoFilter").is_some(), - filter: x.child("autoFilter").and_then(|e| read_autofilter(cx, e)).map(|af| af.criteria).unwrap_or_default(), - table_type: xml_table.then(|| "xml".to_string()), - connection_id: x.attr_u32("connectionId").filter(|_| xml_table), - }) -} - -pub(super) fn read_comments(x: &El, sheet: &mut Sheet) { - let authors: Vec = x.child("authors").map(|a| a.kids("author").map(|a| a.text.clone()).collect()).unwrap_or_default(); - let Some(list) = x.child("commentList") else { return }; - for c in list.kids("comment") { - let Some(cell) = c.attr("ref").and_then(CellRef::parse) else { continue }; - let author = c.attr_u32("authorId").and_then(|i| authors.get(i as usize)).cloned().unwrap_or_default(); - let mut text = c.child("text").map(xml::rich_text).unwrap_or_default(); - // Excel starts a note with a bold "Author:" line. - if !author.is_empty() - && let Some(rest) = text.strip_prefix(&format!("{author}:")) - { - text = rest.strip_prefix('\n').unwrap_or(rest).to_string(); - } - sheet - .comments - .insert(cell, Comment { author, text, replies: vec![], threaded: false, resolved: false, visible: false, dates: vec![], note_box: None }); - } -} - -/// Reads the notes' VML shapes: a shape carrying `` marks its note as shown, and its -/// `` and style size become the note's box. Shapes may sit in groups. -pub(super) fn read_note_shapes(x: &El, sheet: &mut Sheet, depth: usize) { - if depth > xml::MAX_DEPTH { - return; - } - for e in &x.children { - if e.name != "shape" { - read_note_shapes(e, sheet, depth + 1); - continue; - } - let Some(cd) = e.child("ClientData").filter(|cd| cd.attr("ObjectType") == Some("Note")) else { continue }; - let num = |k: &str| cd.child(k).and_then(|v| v.text.trim().parse::().ok()); - let (Some(row), Some(col)) = (num("Row"), num("Column")) else { continue }; - let cell = CellRef::new(row, col); - let Some(c) = sheet.comments.get_mut(&cell) else { continue }; - if cd.child("Visible").is_some() && !c.threaded { - c.visible = true; - } - if let Some(anchor) = cd.child("Anchor") { - c.note_box = note_box(&anchor.text, e.attr("style").unwrap_or(""), cell).filter(|b| *b != crate::sheet_write::DEFAULT_NOTE_BOX); - } - } -} - -/// A note's box from its VML `` (`LeftColumn, LeftOffset, TopRow, TopOffset, -/// RightColumn, RightOffset, BottomRow, BottomOffset`; offsets in pixels) and its shape's style, -/// the corners made relative to the note's `cell`. `None` when the anchor isn't eight in-sheet -/// numbers. -fn note_box(anchor: &str, style: &str, cell: CellRef) -> Option { - let v: Vec = anchor.split(',').map(|p| p.trim().parse::().ok()).collect::>()?; - let [c1, dx1, r1, dy1, c2, dx2, r2, dy2] = <[u32; 8]>::try_from(v).ok()?; - if c1.max(c2) >= MAX_COLS || r1.max(r2) >= MAX_ROWS { - return None; - } - let corner = |c: u32, dx: u32, r: u32, dy: u32| NoteCorner { - col: i64::from(c) - i64::from(cell.col), - col_px: dx, - row: i64::from(r) - i64::from(cell.row), - row_px: dy, - }; - let pt = |key: &str| { - style - .split(';') - .filter_map(|d| d.split_once(':')) - .find(|(k, _)| k.trim().eq_ignore_ascii_case(key)) - .and_then(|(_, v)| v.trim().strip_suffix("pt")?.trim().parse::().ok().filter(|n| n.is_finite() && *n > 0.0 && *n < 1e6)) - }; - Some(NoteBox { from: corner(c1, dx1, r1, dy1), to: corner(c2, dx2, r2, dy2), size_pt: pt("width").zip(pt("height")) }) -} - pub(super) fn read_threaded(cx: &Ctx<'_>, x: &El, sheet: &mut Sheet) { let mut by_id: HashMap = HashMap::new(); let mut replies: Vec<(String, String, String, String)> = vec![]; diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index 9a81f47bb..0de46e32f 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -3,6 +3,13 @@ use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::fmt::Write as _; +use craft_xlsx::{ + Break as CraftBreak, Cell as CraftCell, CellError as CraftCellError, CellFormula as CraftFormula, CellRef as CraftCellRef, + CellValue as CraftValue, Column as CraftColumn, ConditionalFormatting as CraftCf, DataValidations as CraftDvs, Features as CraftFeatures, + FormulaKind as CraftFormulaKind, HeaderFooter as CraftHf, Hyperlink as CraftHyperlink, PageMargins as CraftMargins, PageSetup as CraftPageSetup, + Pane as CraftPane, Print as CraftPrint, PrintOptions as CraftPrintOptions, Range as CraftRange, Row as CraftRow, Selection as CraftSelection, + SheetFormat as CraftSheetFormat, SheetPart as CraftSheetPart, SheetView as CraftSheetView, +}; use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value}; use gridcraft_model::{ Cell, CfOperator, CfRule, CfValueKind, Color, CondFormat, ErrorStyle, FilterCriterion, Formula, LineInfo, NoteBox, NoteCorner, Orientation, @@ -17,7 +24,7 @@ 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}; +use crate::xml::{encode_xstring, esc, esc_attr, num}; /// The worksheet extension holding Excel 2010 conditional formats. const EXT_X14_CF: &str = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}"; @@ -33,18 +40,56 @@ fn sqref(ranges: &[RangeRef]) -> String { ranges.iter().map(|r| r.a1()).collect::>().join(" ") } +fn to_craft_cell_ref(c: CellRef) -> CraftCellRef { + CraftCellRef::new(c.row, c.col) +} + +fn to_craft_range(r: RangeRef) -> CraftRange { + CraftRange::new(to_craft_cell_ref(r.start), to_craft_cell_ref(r.end)) +} + +fn to_craft_error(e: CellError) -> CraftCellError { + match e { + CellError::Null => CraftCellError::Null, + CellError::Div0 => CraftCellError::Div0, + CellError::Value => CraftCellError::Value, + CellError::Ref => CraftCellError::Ref, + CellError::Name => CraftCellError::Name, + CellError::Num => CraftCellError::Num, + CellError::NA => CraftCellError::NA, + CellError::GettingData => CraftCellError::GettingData, + CellError::Spill => CraftCellError::Spill, + CellError::Calc => CraftCellError::Calc, + _ => CraftCellError::Value, + } +} + +fn parse_craft_fragment(xml: &str) -> Option { + let opts = craft_xml::Options::default().with_limits(craft_xml::Limits { + max_input: crate::package::MAX_PART as usize, + max_depth: crate::xml::MAX_DEPTH, + max_nodes: crate::xml::MAX_XML_NODES, + ..craft_xml::Limits::DEFAULT + }); + opts.parse(xml.as_bytes()).ok() +} + +fn push_fragment_kids(root: &mut craft_xml::El, xml: &str) { + if xml.is_empty() { + return; + } + let wrapped = format!("{xml}"); + if let Some(parsed) = parse_craft_fragment(&wrapped) { + root.children.extend(parsed.children); + } +} + pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (String, Rels) { let mut rels = Rels::default(); let Some(sheet) = wb.sheet(si) else { return (String::new(), rels) }; let nstyles = wb.styles.len() as u32; let sid = |s: gridcraft_model::StyleId| if s.0 < nstyles { s.0 } else { 0 }; - // A table's dropdown filter is kept in `sheet.autofilter`, not in `Table::filter` (the - // engine's only live filter state, which the reader also fills). Where the two coincide, - // fold the sheet filter's criteria into the table so they reach the file: the stored - // `colId` offsets are relative to the range's first column, and both ranges start at the - // same column, so they carry over verbatim. A filter that only partially covers a table - // has nowhere valid to go, so it keeps being suppressed below. let folded: Vec
= match &sheet.autofilter { Some(af) if !af.criteria.is_empty() => sheet .tables @@ -64,7 +109,6 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( .collect(), _ => sheet.tables.clone(), }; - // Table header cells must hold the column names. let mut overrides: BTreeMap = BTreeMap::new(); let tables: Vec<(&Table, Vec)> = folded .iter() @@ -78,7 +122,6 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( } } } - // Dynamic-array spills: anchor → range, and the spilled values to cache. let dynamic: BTreeMap = sheet .spill_ranges .iter() @@ -88,7 +131,6 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( .map(|(a, r)| (*a, *r)) .collect(); let mut extra: BTreeMap = BTreeMap::new(); - // Values inside spills and legacy array ranges. for (a, r) in sheet.spill_ranges.iter().filter(|(_, r)| !r.is_single()) { for c in r.iter().take(1_000_000) { if c != *a @@ -100,111 +142,61 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( } } - let mut s = format!("{XML_DECL}"); + let mut part = CraftSheetPart { root: craft_xml::El::new("worksheet"), ..Default::default() }; // sheetPr let fit = sheet.print.fit_to.is_some(); let summary = !sheet.summary_below || !sheet.summary_right; if sheet.tab_color.is_some() || fit || summary { - s.push_str(""); + let mut pr = craft_xml::El::new("sheetPr"); if let Some(c) = &sheet.tab_color { - let _ = write!(s, "", color_attrs(c)); + let xml = format!("", color_attrs(c)); + if let Some(el) = parse_craft_fragment(&xml) { + pr.push(el); + } } if summary { - s.push_str(""); + if !sheet.summary_right { + outline.set_attr("summaryRight", "0"); + } + pr.push(outline); } if fit { - s.push_str(""); + pr.push(craft_xml::El::new("pageSetUpPr").with_attr("fitToPage", "1")); } - s.push_str(""); + part.root.push(pr); } - let mut used = sheet.cells.used_range(); - for c in extra.keys().chain(overrides.keys()) { - let r = RangeRef::cell(*c); - used = Some(used.map_or(r, |u| u.union(&r))); - } - let _ = write!(s, "", used.map(|u| u.a1()).unwrap_or_else(|| "A1".into())); - write_sheet_views(&mut s, sheet, selected); - - // sheetFormatPr let max_row_outline = sheet.rows.values().map(|r| r.outline).max().unwrap_or(0); let max_col_outline = sheet.cols.values().map(|r| r.outline).max().unwrap_or(0); - s.push_str(" 0.01 { - let _ = write!(s, " defaultColWidth=\"{}\"", num(px_to_col_width(sheet.default_col_width))); - } - let _ = write!(s, " defaultRowHeight=\"{}\"", num(px_to_pt(sheet.default_row_height))); - if (sheet.default_row_height - gridcraft_model::DEFAULT_ROW_HEIGHT).abs() > 0.01 { - s.push_str(" customHeight=\"1\""); - } - if max_row_outline > 0 { - let _ = write!(s, " outlineLevelRow=\"{max_row_outline}\""); - } - if max_col_outline > 0 { - let _ = write!(s, " outlineLevelCol=\"{max_col_outline}\""); - } - s.push_str("/>"); + part.features.format = Some(CraftSheetFormat { + default_col_width: ((sheet.default_col_width - gridcraft_model::DEFAULT_COL_WIDTH).abs() > 0.01) + .then(|| px_to_col_width(sheet.default_col_width)), + default_row_height: Some(px_to_pt(sheet.default_row_height)), + custom_height: ((sheet.default_row_height - gridcraft_model::DEFAULT_ROW_HEIGHT).abs() > 0.01).then_some(true), + outline_level_row: (max_row_outline > 0).then_some(u32::from(max_row_outline)), + outline_level_col: (max_col_outline > 0).then_some(u32::from(max_col_outline)), + ..Default::default() + }); - // cols: runs of identical settings. - if !sheet.cols.is_empty() { - s.push_str(""); - let mut run: Option<(u32, u32, LineInfo)> = None; - let flush = |s: &mut String, r: (u32, u32, LineInfo)| { - let (a, b, i) = r; - let w = i.size.unwrap_or(sheet.default_col_width); - let _ = write!(s, "0 { - let _ = write!(s, " outlineLevel=\"{}\"", i.outline.min(7)); - } - if i.collapsed { - s.push_str(" collapsed=\"1\""); - } - s.push_str("/>"); - }; - for (&c, info) in &sheet.cols { - if c >= gridcraft_core::MAX_COLS { - continue; - } - run = match run { - Some((a, b, i)) if b + 1 == c && i == *info => Some((a, c, i)), - Some(r) => { - flush(&mut s, r); - Some((c, c, *info)) - } - None => Some((c, c, *info)), - }; - } - if let Some(r) = run { - flush(&mut s, r); - } - s.push_str(""); - } + part.features.views = vec![build_craft_view(sheet, selected)]; + part.columns = build_craft_cols(sheet, &sid); + part.merges = sheet.merges.iter().filter(|m| !m.is_single()).copied().map(to_craft_range).collect(); - write_sheet_data(&mut s, SheetCellData { workbook: wb, index: si, sheet, overrides: &overrides, extra: &extra, dynamic: &dynamic }, &sid, out); + let rows = build_craft_rows(SheetCellData { workbook: wb, index: si, sheet, overrides: &overrides, extra: &extra, dynamic: &dynamic }, &sid, out); - let x14_cf = write_sheet_rules(&mut s, sheet, &mut rels, out); - let kept = write_sheet_printing(&mut s, sheet, &mut rels, out); + let (rules_frag, x14_cf) = build_sheet_rules(sheet, &mut part.features, &mut rels, out); + push_fragment_kids(&mut part.root, &rules_frag); + + let kept = build_sheet_printing(sheet, &mut part.features.print, &mut rels, out); + part.features.drawing = write_sheet_drawing_rel(wb, si, sheet, &mut rels, out); + let (legacy_rid, notes_frag) = write_sheet_notes_frag(sheet, si, &kept, &mut rels, out); + part.features.legacy_drawing = legacy_rid; - write_sheet_drawing(&mut s, wb, si, sheet, &mut rels, out); - write_sheet_notes(&mut s, sheet, si, &kept, &mut rels, out); - // Tables. if !tables.is_empty() { - let mut parts = String::new(); let mut used_names: HashSet = HashSet::new(); for (t, cols) in &tables { out.tables += 1; @@ -213,14 +205,126 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> ( let name = table_name(&t.name, &mut used_names, out.table_id); let xml = table_xml(t, cols, &name, out.table_id, out); out.part(&format!("xl/tables/table{n}.xml"), Some(CT_TABLE), xml.into_bytes()); - let rid = rels.add("table", &format!("../tables/table{n}.xml")); - let _ = write!(parts, ""); + part.features.table_parts.push(rels.add("table", &format!("../tables/table{n}.xml"))); } - let _ = write!(s, "{parts}", tables.len()); } - write_sheet_extensions(&mut s, sheet, &x14_cf); - s.push_str(""); - (s, rels) + + let mut ext_xml = String::new(); + write_sheet_extensions(&mut ext_xml, sheet, &x14_cf); + push_fragment_kids(&mut part.root, &ext_xml); + + let mut xml = String::from_utf8(part.to_xml(&rows)).unwrap_or_default(); + if !notes_frag.is_empty() { + let after_data = xml + .find("") + .map(|p| p + "".len()) + .or_else(|| xml.find("").map(|p| p + "".len())) + .unwrap_or(0); + let pos = [""] + .iter() + .filter_map(|tag| xml[after_data..].find(tag).map(|p| after_data + p)) + .min() + .unwrap_or(xml.len()); + xml.insert_str(pos, ¬es_frag); + } + (xml, rels) +} + +fn build_craft_cols(sheet: &Sheet, sid: &dyn Fn(gridcraft_model::StyleId) -> u32) -> Vec { + let mut cols = Vec::new(); + let mut run: Option<(u32, u32, LineInfo)> = None; + let push_run = |cols: &mut Vec, (a, b, i): (u32, u32, LineInfo)| { + let w = i.size.unwrap_or(sheet.default_col_width); + cols.push(CraftColumn { + first: a, + last: b, + width: Some(px_to_col_width(w)), + custom_width: i.size.is_some(), + best_fit: false, + hidden: i.hidden, + outline_level: i.outline.min(7), + collapsed: i.collapsed, + style: i.style.map(sid), + }); + }; + for (&c, info) in &sheet.cols { + if c >= gridcraft_core::MAX_COLS { + continue; + } + run = match run { + Some((a, b, i)) if b + 1 == c && i == *info => Some((a, c, i)), + Some(r) => { + push_run(&mut cols, r); + Some((c, c, *info)) + } + None => Some((c, c, *info)), + }; + } + if let Some(r) = run { + push_run(&mut cols, r); + } + cols +} + +fn build_craft_view(sheet: &Sheet, selected: bool) -> CraftSheetView { + let active = sheet.view_active.a1(); + let (pane, selections) = match sheet.freeze { + Some((rows, cols)) if rows > 0 || cols > 0 => { + let pane_name = match (rows > 0, cols > 0) { + (true, true) => "bottomRight", + (true, false) => "bottomLeft", + _ => "topRight", + }; + let top_left = CellRef::new( + rows.max(sheet.view_top_left.row).min(gridcraft_core::MAX_ROWS - 1), + cols.max(sheet.view_top_left.col).min(gridcraft_core::MAX_COLS - 1), + ) + .a1(); + let pane = CraftPane { + x_split: (cols > 0).then_some(f64::from(cols)), + y_split: (rows > 0).then_some(f64::from(rows)), + top_left_cell: Some(top_left), + active_pane: Some(pane_name.to_string()), + state: Some("frozen".to_string()), + ..Default::default() + }; + let sel = CraftSelection { + pane: Some(pane_name.to_string()), + active_cell: Some(active), + active_cell_id: None, + sqref: vec![to_craft_range(RangeRef::cell(sheet.view_active))], + ..Default::default() + }; + (Some(pane), vec![sel]) + } + _ => { + let sel = CraftSelection { + pane: None, + active_cell: Some(active), + active_cell_id: None, + sqref: vec![to_craft_range(RangeRef::cell(sheet.view_active))], + ..Default::default() + }; + (None, vec![sel]) + } + }; + CraftSheetView { + tab_selected: selected.then_some(true), + show_grid_lines: (!sheet.show_gridlines).then_some(false), + show_row_col_headers: (!sheet.show_headings).then_some(false), + show_formulas: sheet.show_formulas.then_some(true), + show_zeros: (!sheet.show_zeros).then_some(false), + show_outline_symbols: (!sheet.show_outline_symbols).then_some(false), + right_to_left: sheet.right_to_left.then_some(true), + view: (sheet.view != gridcraft_model::SheetViewMode::Normal).then(|| sheet.view.as_str().to_string()), + zoom_scale: (sheet.zoom != 100 && (10..=400).contains(&sheet.zoom)).then_some(u32::from(sheet.zoom)), + zoom_scale_normal: (sheet.zoom != 100 && (10..=400).contains(&sheet.zoom)).then_some(u32::from(sheet.zoom)), + top_left_cell: (sheet.view_top_left != CellRef::default() && sheet.freeze.is_none()).then(|| sheet.view_top_left.a1()), + workbook_view_id: Some(0), + pane, + selections, + ..Default::default() + } } struct CellWriteInput<'a> { @@ -266,20 +370,20 @@ fn write_sheet_extensions(s: &mut String, sheet: &Sheet, x14_cf: &str) { } } -fn write_sheet_notes(s: &mut String, sheet: &Sheet, si: usize, kept: &crate::passthrough::SheetKept<'_>, rels: &mut Rels, out: &mut Out) { - // Notes and form controls share one legacy VML drawing: notes need it for Excel to show them, - // and controls carry their `x:ClientData` there. Shape ids come from 1024-id blocks listed in - // the drawing's idmap (after the blocks kept header and footer drawings use), notes first, so - // a control's `shapeId` names its VML shape. Threaded comments also get a legacy note (its - // text with the replies as lines, for readers without threaded comments) linked by id. +fn write_sheet_notes_frag( + sheet: &Sheet, + si: usize, + kept: &crate::passthrough::SheetKept<'_>, + rels: &mut Rels, + out: &mut Out, +) -> (Option, String) { let mut controls = String::new(); - if !sheet.comments.is_empty() || !sheet.controls.is_empty() { + let legacy_rid = if !sheet.comments.is_empty() || !sheet.controls.is_empty() { let shapes = (sheet.comments.len() as u64).saturating_add(sheet.controls.len() as u64); let blocks = u32::try_from(shapes.saturating_add(1).div_ceil(1024)).unwrap_or(u32::MAX).max(1); let first = out.kept.notes_block(out.vml_block.saturating_add(1)); out.vml_block = out.vml_block.saturating_add(blocks); let idmap = (first..first.saturating_add(blocks)).map(|b| b.to_string()).collect::>().join(","); - // With a kept drawing, our shapes join it in a block of their own. let base = kept.shape_base().unwrap_or(u64::from(first) * 1024); let notes = sheet.comments.len() as u64; let mut control_shapes = String::new(); @@ -306,160 +410,127 @@ fn write_sheet_notes(s: &mut String, sheet: &Sheet, si: usize, kept: &crate::pas let vml_name = format!("xl/drawings/vmlDrawing{v}.vml"); let vml = kept.notes_vml(vml_xml(sheet, &idmap, base, &control_shapes), &vml_name, out); out.part(&vml_name, None, vml.into_bytes()); - let rid = rels.add("vmlDrawing", &format!("../drawings/vmlDrawing{v}.vml")); - let _ = write!(s, ""); - } else if let Some(rid) = kept.lone_vml(rels, out) { - let _ = write!(s, ""); - } - s.push_str(&kept.elements(&controls)); + Some(rels.add("vmlDrawing", &format!("../drawings/vmlDrawing{v}.vml"))) + } else { + kept.lone_vml(rels, out) + }; + (legacy_rid, kept.elements(&controls)) } -fn write_sheet_drawing(s: &mut String, wb: &Workbook, si: usize, sheet: &Sheet, rels: &mut Rels, out: &mut Out) { - // Drawing: pictures, charts, shapes. - if !sheet.images.is_empty() || !sheet.charts.is_empty() || !sheet.shapes.is_empty() { - out.drawings += 1; - let dn = out.drawings; - let mut drels = Rels::default(); - let mut objs: Vec> = vec![]; - for img in &sheet.images { - if img.data.is_empty() { - continue; - } - let ext = image_ext(&img.mime, &img.data); - out.default_type(ext, image_content_type(ext)); - let file = out.image_part(ext, &img.data); - let rid = drels.add("image", &format!("../media/{file}")); - objs.push(Obj::Image(img, rid)); - } - for ch in &sheet.charts { - out.charts += 1; - let rid = if crate::chartex::is_chartex(ch.kind) { - let n = out.charts; - let xml = crate::chartex::write_chartex(wb, si, ch, &mut out.chart_names); - out.part(&format!("xl/charts/chartEx{n}.xml"), Some(crate::chartex::CT_CHARTEX), xml.into_bytes()); - // Excel expects a chartex part's style and colour parts. - out.part(&format!("xl/charts/style{n}.xml"), Some(crate::chartex::CT_STYLE), crate::chartex::style_xml().into_bytes()); - out.part(&format!("xl/charts/colors{n}.xml"), Some(crate::chartex::CT_COLORS), crate::chartex::colors_xml().into_bytes()); - let mut crels = Rels::default(); - crels.add_uri(crate::chartex::REL_STYLE, &format!("style{n}.xml")); - crels.add_uri(crate::chartex::REL_COLORS, &format!("colors{n}.xml")); - out.part(&format!("xl/charts/_rels/chartEx{n}.xml.rels"), None, crels.xml().into_bytes()); - drels.add_uri(crate::chartex::REL_CHARTEX, &format!("../charts/chartEx{n}.xml")) - } else { - let name = format!("xl/charts/chart{}.xml", out.charts); - out.part(&name, Some(CT_CHART), crate::chart::write_chart(wb, si, ch, &out.book_name).into_bytes()); - drels.add("chart", &format!("../charts/chart{}.xml", out.charts)) - }; - objs.push(Obj::Chart(ch, rid)); - } - for sh in &sheet.shapes { - objs.push(Obj::Shape(sh)); - } - out.part(&format!("xl/drawings/drawing{dn}.xml"), Some(CT_DRAWING), crate::drawing::write_drawing(sheet, &wb.theme, &objs).into_bytes()); - if !drels.is_empty() { - out.part(&format!("xl/drawings/_rels/drawing{dn}.xml.rels"), None, drels.xml().into_bytes()); - } - let rid = rels.add("drawing", &format!("../drawings/drawing{dn}.xml")); - let _ = write!(s, ""); +fn write_sheet_drawing_rel(wb: &Workbook, si: usize, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> Option { + if sheet.images.is_empty() && sheet.charts.is_empty() && sheet.shapes.is_empty() { + return None; } + out.drawings += 1; + let dn = out.drawings; + let mut drels = Rels::default(); + let mut objs: Vec> = vec![]; + for img in &sheet.images { + if img.data.is_empty() { + continue; + } + let ext = image_ext(&img.mime, &img.data); + out.default_type(ext, image_content_type(ext)); + let file = out.image_part(ext, &img.data); + let rid = drels.add("image", &format!("../media/{file}")); + objs.push(Obj::Image(img, rid)); + } + for ch in &sheet.charts { + out.charts += 1; + let rid = if crate::chartex::is_chartex(ch.kind) { + let n = out.charts; + let xml = crate::chartex::write_chartex(wb, si, ch, &mut out.chart_names); + out.part(&format!("xl/charts/chartEx{n}.xml"), Some(crate::chartex::CT_CHARTEX), xml.into_bytes()); + out.part(&format!("xl/charts/style{n}.xml"), Some(crate::chartex::CT_STYLE), crate::chartex::style_xml().into_bytes()); + out.part(&format!("xl/charts/colors{n}.xml"), Some(crate::chartex::CT_COLORS), crate::chartex::colors_xml().into_bytes()); + let mut crels = Rels::default(); + crels.add_uri(crate::chartex::REL_STYLE, &format!("style{n}.xml")); + crels.add_uri(crate::chartex::REL_COLORS, &format!("colors{n}.xml")); + out.part(&format!("xl/charts/_rels/chartEx{n}.xml.rels"), None, crels.xml().into_bytes()); + drels.add_uri(crate::chartex::REL_CHARTEX, &format!("../charts/chartEx{n}.xml")) + } else { + let name = format!("xl/charts/chart{}.xml", out.charts); + out.part(&name, Some(CT_CHART), crate::chart::write_chart(wb, si, ch, &out.book_name).into_bytes()); + drels.add("chart", &format!("../charts/chart{}.xml", out.charts)) + }; + objs.push(Obj::Chart(ch, rid)); + } + for sh in &sheet.shapes { + objs.push(Obj::Shape(sh)); + } + out.part(&format!("xl/drawings/drawing{dn}.xml"), Some(CT_DRAWING), crate::drawing::write_drawing(sheet, &wb.theme, &objs).into_bytes()); + if !drels.is_empty() { + out.part(&format!("xl/drawings/_rels/drawing{dn}.xml.rels"), None, drels.xml().into_bytes()); + } + Some(rels.add("drawing", &format!("../drawings/drawing{dn}.xml"))) } -fn write_sheet_printing<'a>(s: &mut String, sheet: &'a Sheet, rels: &mut Rels, out: &mut Out) -> crate::passthrough::SheetKept<'a> { - // Printing. +fn build_sheet_printing<'a>(sheet: &'a Sheet, print: &mut CraftPrint, rels: &mut Rels, out: &mut Out) -> crate::passthrough::SheetKept<'a> { let p = &sheet.print; if p.gridlines || p.headings || p.center_h || p.center_v { - s.push_str(""); + print.options = Some(CraftPrintOptions { + horizontal_centered: p.center_h.then_some(true), + vertical_centered: p.center_v.then_some(true), + headings: p.headings.then_some(true), + grid_lines: p.gridlines.then_some(true), + grid_lines_set: None, + ..Default::default() + }); } - // Unmodelled content kept from the source file (printer settings, controls, OLE objects…). let kept = crate::passthrough::SheetKept::write(sheet, rels, out); - // Margins are kept as f32: widen each through its shortest decimal, so 0.3 is written as - // `0.3`, as Excel writes it, and not as `0.30000001192092896` (#1609). let m = |i: usize| { let inches = p.margins.get(i).copied().unwrap_or(0.75); - num(inches.to_string().parse::().unwrap_or(f64::from(inches))) + inches.to_string().parse::().unwrap_or(f64::from(inches)) }; - let _ = - write!(s, "", m(0), m(1), m(2), m(3), m(4), m(5)); - s.push_str(""); + print.margins = Some(CraftMargins { + left: Some(m(0)), + right: Some(m(1)), + top: Some(m(2)), + bottom: Some(m(3)), + header: Some(m(4)), + footer: Some(m(5)), + ..Default::default() + }); + print.setup = Some(CraftPageSetup { + paper_size: paper_id(&p.paper).filter(|&id| id != 1), + scale: (p.scale != 100 && (10..=400).contains(&p.scale)).then_some(u32::from(p.scale)), + first_page_number: p.first_page_number, + fit_to_width: p.fit_to.map(|(w, _)| u32::from(w)), + fit_to_height: p.fit_to.map(|(_, h)| u32::from(h)), + page_order: (p.page_order != PageOrder::DownThenOver).then(|| p.page_order.id().to_string()), + orientation: Some(if p.orientation == Orientation::Landscape { "landscape" } else { "portrait" }.to_string()), + use_first_page_number: p.first_page_number.map(|_| true), + rel_id: kept.page_setup_id().map(str::to_string), + ..Default::default() + }); if p.has_header_footer() || p.different_first || p.different_odd_even || !p.hf_scale_with_doc || !p.hf_align_with_margins { - s.push_str("'); - // CT_HeaderFooter's element order. - for (tag, text) in [ - ("oddHeader", &p.header), - ("oddFooter", &p.footer), - ("evenHeader", &p.even_header), - ("evenFooter", &p.even_footer), - ("firstHeader", &p.first_header), - ("firstFooter", &p.first_footer), - ] { - if !text.is_empty() { - let _ = write!(s, "<{tag}>{}", esc(text)); - } - } - s.push_str(""); + let opt = |t: &String| (!t.is_empty()).then(|| t.clone()); + print.header_footer = Some(CraftHf { + different_odd_even: p.different_odd_even.then_some(true), + different_first: p.different_first.then_some(true), + scale_with_doc: (!p.hf_scale_with_doc).then_some(false), + align_with_margins: (!p.hf_align_with_margins).then_some(false), + odd_header: opt(&p.header), + odd_footer: opt(&p.footer), + even_header: opt(&p.even_header), + even_footer: opt(&p.even_footer), + first_header: opt(&p.first_header), + first_footer: opt(&p.first_footer), + ..Default::default() + }); } - for (tag, list, max) in [("rowBreaks", &p.row_breaks, 16383u32), ("colBreaks", &p.col_breaks, 1048575)] { - let list: Vec = list.iter().copied().filter(|&b| b > 0).collect(); - if !list.is_empty() { - let _ = write!(s, "<{tag} count=\"{0}\" manualBreakCount=\"{0}\">", list.len()); - for b in list { - let _ = write!(s, ""); - } - let _ = write!(s, ""); - } - } - + let to_breaks = |list: &[u32], max: u32| { + list.iter().copied().filter(|&b| b > 0).map(|id| CraftBreak { id: Some(id), max: Some(max), man: Some(true), ..Default::default() }).collect() + }; + print.row_breaks = to_breaks(&p.row_breaks, 16383); + print.col_breaks = to_breaks(&p.col_breaks, 1048575); kept } -fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut Out) -> String { - // sheetProtection +fn build_sheet_rules(sheet: &Sheet, features: &mut CraftFeatures, rels: &mut Rels, out: &mut Out) -> (String, String) { + let mut frag = String::new(); if let Some(p) = &sheet.protection { - s.push_str(""); + frag.push_str("/>"); } - s.push_str(&protected_ranges_xml(sheet)); - // autoFilter (a sheet filter overlapping a table would be invalid). + frag.push_str(&protected_ranges_xml(sheet)); if let Some(af) = &sheet.autofilter && !sheet.tables.iter().any(|t| t.range.intersects(&af.range)) { - s.push_str(&autofilter_xml(af.range, &af.criteria, out)); + frag.push_str(&autofilter_xml(af.range, &af.criteria, out)); } - if !sheet.merges.is_empty() { - let merges: Vec<&RangeRef> = sheet.merges.iter().filter(|m| !m.is_single()).collect(); - let _ = write!(s, "", merges.len()); - for m in merges { - let _ = write!(s, "", m.a1()); - } - s.push_str(""); - } - // Conditional formats, priorities renumbered 1..n in priority order. + let mut order: Vec = (0..sheet.cond_formats.len()).collect(); order.sort_by_key(|&i| sheet.cond_formats.get(i).map(|c| c.priority).unwrap_or(0)); let mut prio = vec![0u32; sheet.cond_formats.len()]; @@ -510,13 +572,6 @@ 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() { @@ -526,8 +581,11 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O let x14 = match x14_cf_rule_xml(cf, &sheet.name, priority, out) { Some(rule) => Some(rule), None => { - let _ = - write!(s, "{}", sqref(&cf.ranges), cf_rule_xml(cf, priority, out)); + let xml = + format!("{}", sqref(&cf.ranges), cf_rule_xml(cf, priority, out)); + if let Some(el) = parse_craft_fragment(&xml) { + features.conditional_formats.push(CraftCf::read(&el)); + } solid_bar_x14(cf, priority) } }; @@ -541,48 +599,41 @@ fn write_sheet_rules(s: &mut String, sheet: &Sheet, rels: &mut Rels, out: &mut O } let vals: Vec<&Validation> = sheet.validations.iter().filter(|v| !v.ranges.is_empty()).collect(); if !vals.is_empty() { - let _ = write!(s, "", vals.len()); - for v in vals { - s.push_str(&validation_xml(v)); - } - s.push_str(""); + let items = vals.iter().filter_map(|v| parse_craft_fragment(&validation_xml(v)).map(|el| craft_xlsx::DataValidation::read(&el))).collect(); + features.validations = Some(CraftDvs { items, ..Default::default() }); } - if !sheet.hyperlinks.is_empty() { - s.push_str(""); - for (c, h) in &sheet.hyperlinks { - let t = h.target.trim(); - if t.is_empty() { - continue; - } - // `external` is what the file said, or what Insert › Link chose; the scheme test covers - // links made before the flag existed. - let external = h.external - || t.contains("://") - || t.to_ascii_lowercase().starts_with("mailto:") - || t.starts_with("\\\\") - || t.to_ascii_lowercase().starts_with("file:"); - let _ = write!(s, " (u, Some(l)), - _ => (t, None), - }; - let id = rels.add_external("hyperlink", url); - let _ = write!(s, " r:id=\"{id}\""); - if let Some(l) = loc { - let _ = write!(s, " location=\"{}\"", esc_attr(l)); - } - } else { - let _ = write!(s, " location=\"{}\" display=\"{}\"", esc_attr(t.trim_start_matches('#')), esc_attr(t.trim_start_matches('#'))); - } - if let Some(tt) = &h.tooltip { - let _ = write!(s, " tooltip=\"{}\"", esc_attr(tt)); - } - s.push_str("/>"); + for (c, h) in &sheet.hyperlinks { + let t = h.target.trim(); + if t.is_empty() { + continue; } - s.push_str(""); + let external = h.external + || t.contains("://") + || t.to_ascii_lowercase().starts_with("mailto:") + || t.starts_with("\\\\") + || t.to_ascii_lowercase().starts_with("file:"); + let (rel_id, location, display, url) = if external { + let (u, loc) = match t.split_once('#') { + Some((u, l)) if !u.is_empty() => (u, Some(l.to_string())), + _ => (t, None), + }; + let id = rels.add_external("hyperlink", u); + (Some(id), loc, None, Some(u.to_string())) + } else { + let loc = t.trim_start_matches('#').to_string(); + (None, Some(loc.clone()), Some(loc), None) + }; + features.hyperlinks.push(CraftHyperlink { + rel_id, + location, + tooltip: h.tooltip.clone(), + display, + range: to_craft_range(RangeRef::cell(*c)), + url, + ..Default::default() + }); } - x14_cf + (frag, x14_cf) } struct SheetCellData<'a> { @@ -594,9 +645,8 @@ struct SheetCellData<'a> { dynamic: &'a BTreeMap, } -fn write_sheet_data(s: &mut String, data: SheetCellData<'_>, sid: &dyn Fn(gridcraft_model::StyleId) -> u32, out: &mut Out) { +fn build_craft_rows(data: SheetCellData<'_>, sid: &dyn Fn(gridcraft_model::StyleId) -> u32, out: &mut Out) -> Vec { let SheetCellData { workbook, index, sheet, overrides, extra, dynamic } = data; - // Cell storage is already row-major; sort only when extra cells need merging. let mut keys: Vec<(CellRef, Option<&Cell>)> = Vec::with_capacity(sheet.cells.len()); keys.extend(sheet.cells.iter().map(|(c, cell)| (c, Some(cell)))); if !sheet.cell_pictures.is_empty() || !extra.is_empty() || !overrides.is_empty() || !keys.is_sorted_by_key(|(c, _)| *c) { @@ -606,8 +656,7 @@ fn write_sheet_data(s: &mut String, data: SheetCellData<'_>, sid: &dyn Fn(gridcr all.extend(overrides.keys().copied()); keys = all.into_iter().map(|c| (c, sheet.cells.get(c))).collect(); } - s.reserve(keys.len().saturating_mul(32)); - s.push_str(""); + let mut rows = Vec::new(); let mut row_infos = sheet.rows.iter().peekable(); let mut next = 0; loop { @@ -631,29 +680,7 @@ fn write_sheet_data(s: &mut String, data: SheetCellData<'_>, sid: &dyn Fn(gridcr if cells.is_empty() && info == LineInfo::default() { continue; } - s.push_str(""); + rows.push(CraftRow { + index: row, + height: info.size.map(px_to_pt), + custom_height: info.size.is_some() && info.custom, + hidden: info.hidden, + outline_level: info.outline.min(7), + collapsed: info.collapsed, + style: info.style.map(sid), + cells: craft_cells, + attrs: Vec::new(), + }); } - s.push_str(""); + rows } -fn write_sheet_views(s: &mut String, sheet: &Sheet, selected: bool) { - s.push_str(""); - let active = sheet.view_active.a1(); - match sheet.freeze { - Some((rows, cols)) if rows > 0 || cols > 0 => { - let pane = match (rows > 0, cols > 0) { - (true, true) => "bottomRight", - (true, false) => "bottomLeft", - _ => "topRight", - }; - s.push_str(" 0 { - let _ = write!(s, " xSplit=\"{cols}\""); - } - if rows > 0 { - let _ = write!(s, " ySplit=\"{rows}\""); - } - let _ = write!( - s, - " topLeftCell=\"{}\" activePane=\"{pane}\" state=\"frozen\"/>", - CellRef::new( - rows.max(sheet.view_top_left.row).min(gridcraft_core::MAX_ROWS - 1), - cols.max(sheet.view_top_left.col).min(gridcraft_core::MAX_COLS - 1) - ) - .a1() - ); - let _ = write!(s, ""); - } - _ => { - let _ = write!(s, ""); - } - } - s.push_str(""); -} - -fn write_cell(s: &mut String, input: CellWriteInput<'_>, sid: &dyn Fn(gridcraft_model::StyleId) -> u32, out: &mut Out) { +fn build_craft_cell(input: CellWriteInput<'_>, sid: &dyn Fn(gridcraft_model::StyleId) -> u32, out: &mut Out) -> CraftCell { let CellWriteInput { reference: c, cell, picture, header_override: ov, spill_value: extra, dynamic_range: dynamic } = input; let style = cell.map(|x| sid(x.style)).unwrap_or(0); - s.push_str("#VALUE!"); - return; + return CraftCell { at, style, value: CraftValue::Error(CraftCellError::Value), value_metadata: Some(vm), ..Default::default() }; } let formula = if ov.is_some() { None } else { cell.and_then(|x| x.formula.as_ref()) }; - // A Python cell is saved as [MS-XLSX] 2.3.10 specifies, `_xlfn._xlws.PY(index,0|1)` with its - // code as script `index` of the Python part, and with its cached value; an application without - // Python shows the value (and #NAME? if it recalculates). let py_text = if ov.is_some() || formula.is_some() { None } else { @@ -798,82 +758,55 @@ fn write_cell(s: &mut String, input: CellWriteInput<'_>, sid: &dyn Fn(gridcraft_ }; let value = match value { Value::Error(CellError::Circ) => Value::Number(0.0), - // #SPILL! and #CALC! are not error codes of the file format (Excel refuses a file that - // caches them); Excel itself caches them as #VALUE!. The Python errors are the same kind. Value::Error(CellError::Spill | CellError::Calc | CellError::Python | CellError::Busy | CellError::Timeout | CellError::Blocked) => { Value::Error(CellError::Value) } v => v, }; - // A formula read with dynamic-array metadata keeps it, even where the shape analysis would - // not need it: Excel decided the formula is evaluated as an array. let own = formula.filter(|f| f.dynamic && f.array.is_none()).map(|_| RangeRef::cell(c)); let dynamic = dynamic.or(own.as_ref()); - // A non-spilling formula may still need array evaluation to avoid implicit intersection. - if dynamic.is_some() && (formula.is_some_and(|f| f.array.is_none()) || py_text.is_some()) { - s.push_str(" cm=\"1\""); + let cell_metadata = if dynamic.is_some() && (formula.is_some_and(|f| f.array.is_none()) || py_text.is_some()) { out.dynamic_arrays = true; - } - let text = formula.map(|f| esc(&crate::fmla::to_file(f))).or_else(|| py_text.map(|t| esc(&t))); + Some(1) + } else { + None + }; + let text = formula.map(|f| crate::fmla::to_file(f)).or(py_text); if let Some(text) = text { - let t = match &value { - Value::Text(_) => " t=\"str\"", - Value::Bool(_) => " t=\"b\"", - Value::Error(_) => " t=\"e\"", - _ => "", + let (kind, range) = match (formula.and_then(|f| f.array), dynamic) { + (Some(r), _) => (CraftFormulaKind::Array, Some(to_craft_range(r))), + (None, Some(r)) => (CraftFormulaKind::Array, Some(to_craft_range(*r))), + _ => (CraftFormulaKind::Normal, None), }; - s.push_str(t); - s.push('>'); - match (formula.and_then(|f| f.array), dynamic) { - (Some(r), _) => { - let _ = write!(s, "{text}", r.a1()); - } - (None, Some(r)) => { - let _ = write!(s, "{text}", r.a1()); - } + let craft_val = match &value { + Value::Number(n) => CraftValue::Number(*n), + Value::Text(t) => CraftValue::Text(t.as_ref().into()), + Value::Bool(b) => CraftValue::Bool(*b), + Value::Error(e) => CraftValue::Error(to_craft_error(*e)), _ => { - let _ = write!(s, "{text}"); + out.needs_calc = true; + CraftValue::Empty } - } - match &value { - Value::Number(n) => { - let _ = write!(s, "{}", num(*n)); - } - Value::Text(t) => { - let _ = write!(s, "{}", esc(&encode_xstring(t))); - } - Value::Bool(b) => { - let _ = write!(s, "{}", *b as u8); - } - Value::Error(e) => { - let _ = write!(s, "{}", e.as_str()); - } - _ => out.needs_calc = true, - } - s.push_str(""); - return; - } - match &value { - Value::Empty | Value::Array(_) => s.push_str("/>"), - Value::Number(n) => { - let _ = write!(s, ">{}", num(*n)); - } - // Text inside a spill or array range is a cached formula result: Excel writes it as `t="str"` - // and shows #VALUE! for a shared string there when it trusts the saved values. - Value::Text(t) if extra.is_some() => { - let _ = write!(s, " t=\"str\">{}", esc(&encode_xstring(t))); - } - Value::Text(t) => { - let i = out.sst.index(t); - let _ = write!(s, " t=\"s\">{i}"); - } - Value::Bool(b) => { - let _ = write!(s, " t=\"b\">{}", *b as u8); - } - Value::Error(e) => { - let _ = write!(s, " t=\"e\">{}", e.as_str()); - } + }; + return CraftCell { + at, + style, + value: craft_val, + formula: Some(CraftFormula { kind, text, shared_index: None, range, attrs: Vec::new() }), + value_metadata: None, + cell_metadata, + phonetic: false, + }; } + let craft_val = match &value { + Value::Empty | Value::Array(_) => CraftValue::Empty, + Value::Number(n) => CraftValue::Number(*n), + Value::Text(t) if extra.is_some() => CraftValue::Text(t.as_ref().into()), + Value::Text(t) => CraftValue::Shared(out.sst.index(t)), + Value::Bool(b) => CraftValue::Bool(*b), + Value::Error(e) => CraftValue::Error(to_craft_error(*e)), + }; + CraftCell { at, style, value: craft_val, ..Default::default() } } const X14_NS: &str = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; diff --git a/crates/xlsx/src/tests/equation_tests.rs b/crates/xlsx/src/tests/equation_tests.rs index 223419768..983f3edfc 100644 --- a/crates/xlsx/src/tests/equation_tests.rs +++ b/crates/xlsx/src/tests/equation_tests.rs @@ -475,7 +475,8 @@ fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() { // the same box as its fallback. Neither takes the (large) size the equation is drawn at. let wb = book(vec![equation(1, "B2", "\\begin{CD} A @>f>> B \\end{CD}", Color::Auto), equation(2, "B8", "x^2", Color::Auto)]); let d = drawing(&unzip(&write_xlsx(&wb).unwrap())); - let text_runs: Vec<&str> = d.match_indices("").unwrap()]).collect(); + let text_runs: Vec<&str> = + d.match_indices("").or_else(|| d[i..].find("/>")).unwrap()]).collect(); assert_eq!(text_runs.len(), 2, "{d}"); for r in text_runs { assert!(r.contains(" sz=\"1100\""), "{r}"); diff --git a/crates/xlsx/src/tests/fixtures.rs b/crates/xlsx/src/tests/fixtures.rs index 7a5cc5676..46a953bc1 100644 --- a/crates/xlsx/src/tests/fixtures.rs +++ b/crates/xlsx/src/tests/fixtures.rs @@ -883,3 +883,44 @@ fn inline_dxf_number_formats_are_shared() { assert_eq!(read.dxfs[0].num_fmt.as_str(), code); assert!(read.dxfs.iter().all(|d| std::sync::Arc::ptr_eq(&d.num_fmt.0, &read.dxfs[0].num_fmt.0))); } + +#[test] +fn two_column_groups_on_different_axes_preserve_secondary_and_kind() { + let drawing = r#" + 000060150 + "#; + let chart = r#" + PrimaryData!$B$2:$B$5 + SecondaryData!$C$2:$C$5 + + "#; + let drels = r#""#; + let srels = r#""#; + let bytes = minimal( + r#""#, + &[ + ("xl/worksheets/_rels/sheet1.xml.rels", srels), + ("xl/drawings/drawing1.xml", drawing), + ("xl/drawings/_rels/drawing1.xml.rels", drels), + ("xl/charts/chart1.xml", chart), + ], + "", + "", + ); + let (wb, _) = read_xlsx(&bytes).unwrap(); + let ch = &wb.sheet(0).unwrap().charts[0]; + assert_eq!(ch.kind, gridcraft_model::ChartKind::Combo); + assert!(!ch.series[0].secondary); + assert!(ch.series[1].secondary); + assert_eq!(ch.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + assert_eq!(ch.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + + let out = crate::write_xlsx(&wb).unwrap(); + let (wb2, _) = read_xlsx(&out).unwrap(); + let ch2 = &wb2.sheet(0).unwrap().charts[0]; + assert_eq!(ch2.kind, gridcraft_model::ChartKind::Combo); + assert!(!ch2.series[0].secondary); + assert!(ch2.series[1].secondary); + assert_eq!(ch2.series[0].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); + assert_eq!(ch2.series[1].kind, Some(gridcraft_model::ChartKind::ColumnClustered)); +} diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 6069ac545..9ec224615 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -2213,3 +2213,85 @@ fn remove_personal_information_is_kept_and_honoured() { assert_eq!(book.child("workbookPr").and_then(|p| p.attr("filterPrivacy")), None); assert!(String::from_utf8(pkg.read("docProps/core.xml").unwrap().unwrap()).unwrap().contains("Jane Example")); } + +#[test] +fn issue_778_xlsx_xml_import_save_reopen_roundtrip() { + let mut wb = Workbook::new(); + let mut s = Sheet::new("Delegated"); + s.cells.set(at("A1"), Cell { value: Value::text("Item"), formula: None, style: StyleId::DEFAULT, py: None }); + s.cells.set(at("B1"), Cell { value: Value::text("Amount"), formula: None, style: StyleId::DEFAULT, py: None }); + s.cells.set(at("A2"), Cell { value: Value::text("Alpha"), formula: None, style: StyleId::DEFAULT, py: None }); + s.cells.set(at("B2"), Cell { value: Value::Number(42.5), formula: None, style: StyleId::DEFAULT, py: None }); + let mut f = Cell::formula(Formula::new("=B2*2")); + f.value = Value::Number(85.0); + s.cells.set(at("B3"), f); + s.merges.push(rr("A4:B4")); + s.hyperlinks.insert(at("A2"), Hyperlink { target: "https://example.com".into(), tooltip: Some("Example".into()), external: true }); + s.comments.insert( + at("B2"), + Comment { + author: "Reviewer".into(), + text: "Checked".into(), + replies: vec![], + threaded: false, + resolved: false, + visible: true, + dates: vec![], + note_box: None, + }, + ); + s.shapes.push(Shape { + id: 1, + kind: ShapeKind::Rectangle, + anchor: Anchor { cell: at("D2"), dx: 4.0, dy: 4.0, width: 120.0, height: 60.0, mode: AnchorMode::MoveAndSize }, + fill: Color::Rgb(0x336699), + line: Color::Rgb(0x112233), + text: "Box".into(), + format: Default::default(), + rotation: 0.0, + math: Default::default(), + }); + s.charts.push(Chart { + id: 2, + kind: ChartKind::ColumnClustered, + anchor: Anchor { cell: at("D6"), dx: 0.0, dy: 0.0, width: 320.0, height: 200.0, mode: AnchorMode::MoveAndSize }, + title: Some("Sales".into()), + series: vec![Series { + name: Some("Delegated!$B$1".into()), + categories: Some("Delegated!$A$2:$A$2".into()), + values: "Delegated!$B$2:$B$2".into(), + ..Default::default() + }], + legend: LegendPos::Bottom, + data_labels: true, + data_table: Some(ChartDataTable::default()), + gridlines: true, + style: 2, + hole_size: 75, + first_slice_angle: 0, + x_title: None, + y_title: None, + source: None, + by_rows: false, + pivot: None, + }); + wb.sheets[0] = Arc::new(s); + + let bytes = write_xlsx(&wb).unwrap(); + let (reopened, _) = read_xlsx(&bytes).unwrap(); + let bytes2 = write_xlsx(&reopened).unwrap(); + let (again, _) = read_xlsx(&bytes2).unwrap(); + + let sh = &again.sheets[0]; + assert_eq!(sh.cells.get(at("A2")).unwrap().value, Value::text("Alpha")); + assert_eq!(sh.cells.get(at("B3")).unwrap().value, Value::Number(85.0)); + assert_eq!(sh.cells.get(at("B3")).unwrap().formula.as_ref().map(|f| f.text.as_str()), Some("B2*2")); + assert_eq!(sh.merges, vec![rr("A4:B4")]); + assert_eq!(sh.hyperlinks.get(&at("A2")).map(|h| h.target.as_str()), Some("https://example.com")); + assert_eq!(sh.comments.get(&at("B2")).map(|c| c.text.as_str()), Some("Checked")); + assert_eq!(sh.shapes.len(), 1); + assert_eq!(sh.shapes[0].text, "Box"); + assert_eq!(sh.charts.len(), 1); + assert_eq!(sh.charts[0].title.as_deref(), Some("Sales")); + assert_eq!(sh.charts[0].data_table, Some(ChartDataTable::default())); +} diff --git a/crates/xlsx/src/xml.rs b/crates/xlsx/src/xml.rs index bb7561a19..372ba07e0 100644 --- a/crates/xlsx/src/xml.rs +++ b/crates/xlsx/src/xml.rs @@ -384,7 +384,8 @@ pub fn push_u64(o: &mut String, mut n: u64) { } /// Appends the `A1`-style text of `c` ([`gridcraft_core::CellRef::a1`]). -pub fn push_a1(o: &mut String, c: gridcraft_core::CellRef) { +#[cfg(test)] +fn push_a1(o: &mut String, c: gridcraft_core::CellRef) { let mut letters = [0u8; 8]; let mut i = letters.len(); let mut n = u64::from(c.col) + 1;