From af8981f5965afc29117c2e458d2cdbce586d0df8 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:13:29 +0100 Subject: [PATCH] craft-drawingml: chart legend entries and engineering-format rounding from DeckCraft (#792) (#1871) --- crates/drawingml/src/chart.rs | 20 ++++++ crates/drawingml/src/chart/read.rs | 47 +++++++++++++ crates/drawingml/src/chart/write.rs | 101 ++++++++++++++++++++++++++++ crates/drawingml/src/numfmt.rs | 27 ++++++-- 4 files changed, 190 insertions(+), 5 deletions(-) diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index e575d10f2..9475d2054 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -354,6 +354,10 @@ pub struct Chart { pub legend: Option, /// `c:legend/c:overlay`: the legend is drawn over the plot instead of shrinking it. pub legend_overlay: bool, + /// `c:legend/c:legendEntry`: entries whose text has its own size, weight or colour, over + /// the legend's. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub legend_entries: Vec, /// Text size in points of the axis labels and legend (from their `c:txPr`, else the chart's); /// `None`: the file gives none. #[serde(skip_serializing_if = "Option::is_none")] @@ -431,6 +435,21 @@ pub struct Chart { pub kept: ChartKept, } +/// One legend entry's own text (`c:legendEntry/c:txPr`): what it sets wins over the legend's. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct LegendEntry { + /// The entry's place in the legend, from 0 (`c:idx`). + pub idx: u32, + /// Text size in points. + #[serde(skip_serializing_if = "Option::is_none")] + pub size: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, +} + /// One relationship of a chart part, with the target string as it was written. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -483,6 +502,7 @@ impl Default for Chart { series: vec![], legend: Some("b".into()), legend_overlay: false, + legend_entries: vec![], text_size: None, title_size: None, data_labels: false, diff --git a/crates/drawingml/src/chart/read.rs b/crates/drawingml/src/chart/read.rs index 38ce9f605..3f2be736f 100644 --- a/crates/drawingml/src/chart/read.rs +++ b/crates/drawingml/src/chart/read.rs @@ -143,6 +143,7 @@ fn chart_within(root: &El, mut budget: usize) -> Option { c.legend = ch.child(Local("legend")).map(|l| l.child(Local("legendPos")).and_then(|c| c.attr_local("val")).unwrap_or("r").to_string()); c.legend_overlay = ch.child(Local("legend")).and_then(|l| l.child(Local("overlay"))).and_then(|o| o.attr_local("val").and_then(value::to_bool)).unwrap_or(false); + c.legend_entries = legend_entries(ch.child(Local("legend"))); c.chart_fill = simple_fill(root.child(Local("spPr"))); c.plot_fill = simple_fill(pa.child(Local("spPr"))); @@ -552,6 +553,52 @@ fn text_color(e: Option<&El>) -> Option { rec(e?, 0) } +/// Legend entries read from one chart; a legend lists at most one per series or category. +const MAX_LEGEND_ENTRIES: usize = 1024; + +/// The legend's entries with text of their own (`c:legendEntry/c:txPr`), over the legend's. +fn legend_entries(legend: Option<&El>) -> Vec { + legend + .into_iter() + .flat_map(|l| l.children(Local("legendEntry"))) + .take(MAX_LEGEND_ENTRIES) + .filter_map(|e| { + // The paragraph's own run properties first, then the list style's defaults + // (`a:lstStyle` comes before `a:p`, and is the less specific of the two). + let tx = e.child(Local("txPr")); + let para = tx.and_then(|t| t.child(Local("p"))); + let entry = crate::chart::LegendEntry { + idx: e.child(Local("idx")).and_then(|i| i.attr_local("val")).and_then(|v| v.parse().ok())?, + size: text_size(para).or_else(|| text_size(tx)), + bold: text_bold(para).or_else(|| text_bold(tx)), + color: text_color(para).or_else(|| text_color(tx)), + }; + (entry.size.is_some() || entry.bold.is_some() || entry.color.is_some()).then_some(entry) + }) + .collect() +} + +/// The weight (`b`) of the first `a:defRPr` or `a:rPr` that sets one under `e`. +fn text_bold(e: Option<&El>) -> Option { + fn rec(e: &El, depth: usize) -> Option { + if depth > 8 { + return None; + } + for c in e.elements() { + if (c.is(Local("defRPr")) || c.is(Local("rPr"))) + && let Some(b) = c.attr_local("b").and_then(value::to_bool) + { + return Some(b); + } + if let Some(v) = rec(c, depth + 1) { + return Some(v); + } + } + None + } + rec(e?, 0) +} + /// The size in points of the first `a:defRPr` or `a:rPr` with one under `e` (`sz` in hundredths). fn text_size(e: Option<&El>) -> Option { fn rec(e: &El, depth: usize) -> Option { diff --git a/crates/drawingml/src/chart/write.rs b/crates/drawingml/src/chart/write.rs index d115c4a2c..6993a6d21 100644 --- a/crates/drawingml/src/chart/write.rs +++ b/crates/drawingml/src/chart/write.rs @@ -101,6 +101,38 @@ fn tx_pr(w: &mut Writer, c: &Chart) { w.close(); } +/// `c:legendEntry` with the entry's own text size, weight and colour. +fn legend_entry(w: &mut Writer, e: &crate::chart::LegendEntry) { + w.open("c:legendEntry", &[]); + w.tag("c:idx").attr("val", e.idx).empty(); + w.open("c:txPr", &[]); + w.empty("a:bodyPr", &[]); + w.empty("a:lstStyle", &[]); + w.open("a:p", &[]); + w.open("a:pPr", &[]); + let mut run = w.tag("a:defRPr"); + if let Some(sz) = e.size.filter(|v| v.is_finite() && *v > 0.0) { + // 1 to 400 pt, as the reader takes it, so a size reads back as written. + run = run.attr("sz", (sz * 100.0).round().clamp(100.0, 40_000.0) as u32); + } + if let Some(b) = e.bold { + run = run.attr("b", u8::from(b)); + } + match &e.color { + Some(c) => { + run.open(); + dml::solid(w, c); + w.close(); + } + None => run.empty(), + } + w.close(); + w.tag("a:endParaRPr").attr("lang", "en-US").empty(); + w.close(); + w.close(); + w.close(); +} + fn rich(w: &mut Writer, text: &str, color: Option<&crate::style::ColorRef>) { w.open("c:tx", &[]); w.open("c:rich", &[]); @@ -781,6 +813,9 @@ pub fn chart_xml(c: &Chart) -> (Vec, bool) { }; w.open("c:legend", &[]); w.tag("c:legendPos").attr("val", p).empty(); + for e in &c.legend_entries { + legend_entry(&mut w, e); + } w.tag("c:overlay").attr("val", u8::from(c.legend_overlay)).empty(); tx_pr(&mut w, c); w.close(); @@ -1058,6 +1093,72 @@ mod tests { use crate::color::{ColorTransform, Rgba}; use crate::style::ColorRef; + /// A legend entry's own text (`c:legendEntry/c:txPr`: size, bold, colour) is read, and a + /// rebuilt part writes it back, in schema order before `c:overlay` (DeckCraft #2067). + #[test] + fn legend_entry_text_is_read_and_survives_an_edit() { + let read = |xml: &[u8]| crate::chart::read::read_chart_xml(xml).unwrap(); + let entry = |idx: u32, rgb: &str| { + format!( + r#""# + ) + }; + let xml = format!( + r#"1{}{}"#, + entry(0, "C00000"), + entry(1, "00B050") + ); + let c = read(xml.as_bytes()); + let want = |idx: u32, rgb: (u8, u8, u8)| crate::chart::LegendEntry { + idx, + size: Some(20.0), + bold: Some(true), + color: Some(ColorRef::rgb(Rgba::rgb(rgb.0, rgb.1, rgb.2))), + }; + // The third entry sets nothing of its own and is not kept. + assert_eq!(c.legend_entries, vec![want(0, (0xC0, 0, 0)), want(1, (0, 0xB0, 0x50))]); + assert_eq!(c.text_size, Some(12.0), "the legend's own size stays the legend's"); + let mut e = c.clone(); + e.title = Some("Units".into()); + e.raw = None; + let (out, kept) = super::chart_xml(&e); + assert!(!kept); + let s = String::from_utf8(out.clone()).unwrap(); + let legend = &s[s.find("").unwrap()..]; + let (pos, entry0, overlay) = + (legend.find("").unwrap(), legend.find(""#, + r#""#, + 1, + ); + assert_ne!(listed, xml, "the list style was put in"); + let c = read(listed.as_bytes()); + assert_eq!(c.legend_entries[0], want(0, (0xC0, 0, 0)), "the paragraph's 20 pt, bold, C00000"); + // The list style alone still counts. + let only_list = + listed.replacen(r#""#, "", 1); + let entry = &read(only_list.as_bytes()).legend_entries[0]; + assert_eq!((entry.size, entry.bold), (Some(12.0), Some(false))); + // A size reads back as it was written, within the reader's 1-400 pt. + for (size, back) in [(20.5, 20.5), (400.0, 400.0), (500.0, 400.0)] { + let mut e = c.clone(); + e.raw = None; + e.legend_entries = vec![crate::chart::LegendEntry { idx: 0, size: Some(size), bold: Some(false), color: None }]; + let written = super::chart_xml(&e).0; + let sz = format!(r#"sz="{}""#, (back * 100.0) as u32); + assert!(String::from_utf8_lossy(&written).contains(&sz), "{size} pt is written as {sz}"); + let back_entry = &read(&written).legend_entries[0]; + assert_eq!((back_entry.size, back_entry.bold), (Some(back), Some(false)), "{size} pt"); + } + } + #[test] fn export_cost_counts_the_caches_each_group_writes() { let s = Series { values: vec![Some(1.0); 600], ..Default::default() }; diff --git a/crates/drawingml/src/numfmt.rs b/crates/drawingml/src/numfmt.rs index b5db9667c..7a7b86665 100644 --- a/crates/drawingml/src/numfmt.rs +++ b/crates/drawingml/src/numfmt.rs @@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option { m *= 10.0; exp -= 1; } - // Rounding the mantissa to its digits can reach 10 (9.999 as `0.00`). - if format!("{m:.mant_frac$}").starts_with("10") { - m /= 10.0; - exp += 1; - } } let step = mant.iter().take_while(|t| **t != Tok::Dot).filter(|t| matches!(t, Tok::Digit(_))).count().max(1) as i32; let shift = exp.rem_euclid(step); exp -= shift; m *= 10f64.powi(shift); + // Round after forming the engineering mantissa: 999.94 as `##0.0` stays 999.9. + // Carry only when rounding exceeds all of the format's integer placeholders. + let carry = 10f64.powi(step); + if format!("{m:.mant_frac$}").parse::().is_ok_and(|rounded| rounded >= carry) { + m /= carry; + exp += step; + } let mantissa = fixed(mant, mfirst, mlast, m, sep, dec); let sign = if exp < 0 { "-" @@ -404,6 +406,21 @@ mod tests { assert_eq!(format("##0.0E+0", 999.96, None), "1.0E+3"); } + #[test] + fn engineering_formats_round_the_full_mantissa() { + for (code, value, expected) in [ + ("##0.0E+00", 999.94, "999.9E+00"), + ("##0.0E+00", 0.99994, "999.9E-03"), + ("##0.0E+00", -999.94, "-999.9E+00"), + ("#0.0E+00", 99.94, "99.9E+00"), + ("##0.0E+00", 999.96, "1.0E+03"), + ("#0.0E+00", 99.96, "1.0E+02"), + ] { + assert_eq!(format(code, value, None), expected, "{code}, {value}"); + } + assert_eq!(format("##0.0E+00", 999.94, Some("de-DE")), "999,9E+00"); + } + #[test] fn never_panics() { for code in ["", ";", ";;;", "\"", "[", "\\", "0.", ".", "#,", "%", "_", "*", "@", "0E+00", "[$", "\"unterminated"] {