diff --git a/crates/engine/src/cf.rs b/crates/engine/src/cf.rs index c49dffccd..8129c52f8 100644 --- a/crates/engine/src/cf.rs +++ b/crates/engine/src/cf.rs @@ -737,6 +737,43 @@ mod tests { assert_eq!([look("A1"), look("A2")], [true, false]); } + #[test] + fn rules_compare_with_cells_on_other_sheets() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "E1", "values": [["Suspended"], ["OK"], ["Terminated"], [7], [3]]})).unwrap(); + let rule = |r: serde_json::Value| json!({"range": "E1:E5", "rule": r}); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$8", "preset": "redText"})), + ) + .unwrap(); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$9", "preset": "redText"})), + ) + .unwrap(); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "expression", "formula": "=AND(ISNUMBER(E1),E1>'Vehicle Range'!$B$1)", "preset": "yellowFill"})), + ) + .unwrap(); + s.execute("home.insertSheet", json!({"name": "Vehicle Range"})).unwrap(); + s.execute("range.setValues", json!({"range": "'Vehicle Range'!A8", "values": [["Suspended"], ["Terminated"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "'Vehicle Range'!B1", "values": [[5]]})).unwrap(); + let d = s.doc().unwrap(); + let report = d.wb.sheets.iter().position(|sh| sh.name != "Vehicle Range").unwrap(); + let mut cache = CfCache::new(); + let mut look = |a: &str| cache.look(&d.wb, report, CellRef::parse(a).unwrap()).and_then(|l| l.style).unwrap_or_default(); + let looks = ["E1", "E2", "E3", "E4", "E5"].map(&mut look); + // The cells equal to 'Vehicle Range'!A8 or A9 get the red text. + let red_text = looks[0].font.color; + assert_ne!(red_text, Color::Auto); + let red = |st: &Style| st.font.color == red_text; + let filled = |st: &Style| st.fill.pattern == PatternType::Solid; + assert_eq!(looks.each_ref().map(red), [true, false, true, false, false]); + assert_eq!(looks.each_ref().map(filled), [false, false, false, true, false]); + } #[test] fn text_rules_skip_error_values() { let mut s = crate::Session::new(); diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index d406c0134..35fd4c881 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -8,7 +8,7 @@ use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRe use gridcraft_formula::Expr; use gridcraft_model::{ AutoFilter, Cell, CfOperator, CfRule, CfValueKind, Comment, CondFormat, EditRange, ErrorStyle, FilterCriterion, Formula, Hyperlink, LineInfo, - NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Table, TableColumn, TotalsFn, + NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Style, Table, TableColumn, TotalsFn, Validation, ValidationKind, XmlColumnPr, }; @@ -25,7 +25,7 @@ mod rules; pub use parts::{read_autofilter, read_table}; use parts::{read_comments, read_hyperlinks, read_note_shapes, read_threaded}; -use rules::{read_cf, read_validation}; +use rules::{read_cf, read_validation, read_x14_cf}; struct Shared { anchor: CellRef, @@ -344,7 +344,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "extLst" => read_ext(cx, e, &mut sheet), + "extLst" => read_ext(cx, e, &mut sheet, &mut cf_kept_cells), "protectedRanges" => read_protected_ranges(e, &mut sheet), _ => {} } @@ -850,7 +850,7 @@ pub fn parse_sqref(s: Option<&str>) -> Vec { } /// Worksheet extensions: x14 data validations and sparklines. -fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { +fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, cf_kept_cells: &mut u64) { for ext in e.kids("ext") { for c in &ext.children { match c.name.as_str() { @@ -878,23 +878,7 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { } } } - "conditionalFormattings" => { - let mut skipped = false; - for r in c.kids("conditionalFormatting").flat_map(|f| f.kids("cfRule")) { - let idx = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id)).map(|(_, n)| *n); - match (idx.and_then(|n| sheet.cond_formats.get_mut(n)), r.child("dataBar")) { - (Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => { - *gradient = db.flag("gradient", true); - // Only the fill style is modelled; borders, lengths, axis or negative colours are lost. - skipped |= db.attrs.iter().any(|(k, _)| k != "gradient") || db.children.iter().any(|k| k.name != "cfvo"); - } - _ => skipped = true, - } - } - if skipped { - cx.warn("some Excel 2010 conditional format extensions were skipped"); - } - } + "conditionalFormattings" => read_x14_cf(cx, c, sheet, cf_kept_cells), _ => {} } } diff --git a/crates/xlsx/src/sheet_read/rules.rs b/crates/xlsx/src/sheet_read/rules.rs index c3a3f04f6..b985953c9 100644 --- a/crates/xlsx/src/sheet_read/rules.rs +++ b/crates/xlsx/src/sheet_read/rules.rs @@ -1,5 +1,5 @@ use super::{ - CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Validation, ValidationKind, from_file, + CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Style, Validation, ValidationKind, from_file, parse_sqref, read_color, }; @@ -57,79 +57,164 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: & for r in e.kids("cfRule") { let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default()); let formulas: Vec = r.kids("formula").map(|f| from_file(f.text.trim())).collect(); - let f0 = formulas.first().cloned().unwrap_or_default(); - let text = r.attr("text").unwrap_or("").to_string(); // The x14 id that links a data bar to its Excel 2010 extension (solid fill lives there). let ext_id = r.child("extLst").and_then(|l| l.kids("ext").find_map(|x| x.child("id"))).map(|i| i.text.trim().to_string()).filter(|i| !i.is_empty()); - let rule = match r.attr("type").unwrap_or("") { - "cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.get(1).cloned(), style }, - "expression" => CfRule::Expression { formula: f0, style }, - "containsText" => CfRule::ContainsText { text, style }, - "notContainsText" => CfRule::NotContainsText { text, style }, - "beginsWith" => CfRule::BeginsWith { text, style }, - "endsWith" => CfRule::EndsWith { text, style }, - "containsBlanks" => CfRule::Blanks { style }, - "notContainsBlanks" => CfRule::NoBlanks { style }, - "containsErrors" => CfRule::Errors { style }, - "notContainsErrors" => CfRule::NoErrors { style }, - "duplicateValues" => CfRule::Duplicate { style }, - "uniqueValues" => CfRule::Unique { style }, - "top10" => { - CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style } - } - "aboveAverage" => CfRule::AboveAverage { - below: !r.flag("aboveAverage", true), - equal: r.flag("equalAverage", false), - std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8, - style, - }, - "timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style }, - "colorScale" => { - let Some(cs) = r.child("colorScale") else { continue }; - let colors = cs.kids("color").map(|c| read_color(c, &cx.palette)); - CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() } - } - "dataBar" => { - let Some(db) = r.child("dataBar") else { continue }; - let v = cfvos(db); - CfRule::DataBar { - min: v.first().cloned().unwrap_or(CfValueKind::Min), - max: v.get(1).cloned().unwrap_or(CfValueKind::Max), - color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(), - gradient: true, - show_value: db.flag("showValue", true), + let ty = r.attr("type").unwrap_or(""); + match cf_rule(cx, r, ty, formulas, style) { + Some(rule) => { + if !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells) { + break; + } + if let Some(id) = ext_id { + cx.cf_ext_ids.push((id, sheet.cond_formats.len() - 1)); } } - "iconSet" => { - let Some(is) = r.child("iconSet") else { continue }; - CfRule::IconSet { - set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(), - thresholds: cfvos(is), - reverse: is.flag("reverse", false), - show_value: is.flag("showValue", true), - } + None if matches!(ty, "colorScale" | "dataBar" | "iconSet") => {} + None => cx.warn(format!("conditional format type \"{ty}\" is not supported")), + } + } +} + +fn push_cf(cx: &mut Ctx<'_>, sheet: &mut Sheet, ranges: &[RangeRef], block_cells: u64, r: &El, rule: CfRule, kept_cells: &mut u64) -> bool { + let total = kept_cells.saturating_add(block_cells); + if total > MAX_COND_CELLS { + cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped")); + return false; + } + *kept_cells = total; + sheet.cond_formats.push(CondFormat { + ranges: ranges.to_vec(), + rule, + priority: r.attr_u32("priority").unwrap_or(0), + stop_if_true: r.flag("stopIfTrue", false), + }); + true +} + +/// The rule of a `cfRule` (main namespace or x14) of type `ty`, given its formulas and +/// differential style; `None` for an unknown type or a scale, bar or icon set without its body. +fn cf_rule(cx: &Ctx<'_>, r: &El, ty: &str, formulas: Vec, style: Box