mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 20:25:02 +00:00
This commit is contained in:
@@ -354,6 +354,10 @@ pub struct Chart {
|
||||
pub legend: Option<String>,
|
||||
/// `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<LegendEntry>,
|
||||
/// 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<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bold: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<ColorRef>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
|
||||
@@ -143,6 +143,7 @@ fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
|
||||
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<crate::style::ColorRef> {
|
||||
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<crate::chart::LegendEntry> {
|
||||
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<bool> {
|
||||
fn rec(e: &El, depth: usize) -> Option<bool> {
|
||||
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<f64> {
|
||||
fn rec(e: &El, depth: usize) -> Option<f64> {
|
||||
|
||||
@@ -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<u8>, 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#"<c:legendEntry><c:idx val="{idx}"/><c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="2000" b="1"><a:solidFill><a:srgbClr val="{rgb}"/></a:solidFill></a:defRPr></a:pPr><a:endParaRPr lang="en-US"/></a:p></c:txPr></c:legendEntry>"#
|
||||
)
|
||||
};
|
||||
let xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><c:chart><c:plotArea><c:lineChart><c:grouping val="standard"/><c:ser><c:idx val="0"/><c:val><c:numRef><c:numCache><c:ptCount val="1"/><c:pt idx="0"><c:v>1</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser><c:axId val="1"/><c:axId val="2"/></c:lineChart><c:catAx><c:axId val="1"/><c:crossAx val="2"/></c:catAx><c:valAx><c:axId val="2"/><c:crossAx val="1"/></c:valAx></c:plotArea><c:legend><c:legendPos val="r"/>{}{}<c:legendEntry><c:idx val="2"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr/></a:pPr></a:p></c:txPr></c:legendEntry><c:overlay val="0"/><c:txPr><a:bodyPr/><a:p><a:pPr><a:defRPr sz="1200"><a:solidFill><a:srgbClr val="7F7F7F"/></a:solidFill></a:defRPr></a:pPr></a:p></c:txPr></c:legend></c:chart></c:chartSpace>"#,
|
||||
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("<c:legend>").unwrap()..];
|
||||
let (pos, entry0, overlay) =
|
||||
(legend.find("<c:legendPos").unwrap(), legend.find("<c:legendEntry>").unwrap(), legend.find("<c:overlay").unwrap());
|
||||
assert!(pos < entry0 && entry0 < overlay, "{s}");
|
||||
assert_eq!(read(&out).legend_entries, c.legend_entries);
|
||||
// None: nothing written.
|
||||
e.legend_entries.clear();
|
||||
assert!(!String::from_utf8(super::chart_xml(&e).0).unwrap().contains("legendEntry"));
|
||||
// The paragraph's own properties win over the list style's, which come first in the XML.
|
||||
let listed = xml.replacen(
|
||||
r#"<c:legendEntry><c:idx val="0"/><c:txPr><a:bodyPr/><a:lstStyle/>"#,
|
||||
r#"<c:legendEntry><c:idx val="0"/><c:txPr><a:bodyPr/><a:lstStyle><a:lvl1pPr><a:defRPr sz="1200" b="0"><a:solidFill><a:srgbClr val="0000FF"/></a:solidFill></a:defRPr></a:lvl1pPr></a:lstStyle>"#,
|
||||
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#"<a:defRPr sz="2000" b="1"><a:solidFill><a:srgbClr val="C00000"/></a:solidFill></a:defRPr>"#, "<a:defRPr/>", 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() };
|
||||
|
||||
@@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option<String> {
|
||||
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::<f64>().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"] {
|
||||
|
||||
Reference in New Issue
Block a user