diff --git a/crates/docx/src/read/chart/model.rs b/crates/docx/src/read/chart/model.rs index fd2760db0..61d5d32d0 100644 --- a/crates/docx/src/read/chart/model.rs +++ b/crates/docx/src/read/chart/model.rs @@ -64,11 +64,46 @@ pub(crate) struct Axis { pub(crate) fmt: Option, /// The axis title, when the file gives it one. pub(crate) title: Option, + /// The title's `a:bodyPr/@rot` in degrees clockwise (`-5400000` is 90° counter-clockwise), + /// when the file gives one. + pub(crate) title_rot: Option, /// Tick labels, as `c:tickLblPos` says (`none` hides them; a file that says nothing shows /// them, as Word does). pub(crate) labels: bool, } +/// The shape of a series' point markers (`ST_MarkerStyle`, ECMA-376 §21.2.3.28). +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] +pub(super) enum Symbol { + #[default] + Circle, + Square, + Diamond, + Triangle, + X, + Plus, + Star, + Dash, + Dot, +} + +impl Symbol { + /// The symbol a `c:symbol` value names; anything unknown (`auto`, `picture`) is a circle. + pub(super) fn parse(name: &str) -> Symbol { + match name { + "square" => Symbol::Square, + "diamond" => Symbol::Diamond, + "triangle" => Symbol::Triangle, + "x" => Symbol::X, + "plus" => Symbol::Plus, + "star" => Symbol::Star, + "dash" => Symbol::Dash, + "dot" => Symbol::Dot, + _ => Symbol::Circle, + } + } +} + pub(super) struct Series { pub(super) name: String, /// The series' `c:idx` (an `xsd:unsignedInt`), which picks its automatic colour; `None` @@ -84,6 +119,10 @@ pub(super) struct Series { pub(super) no_fill: bool, /// Markers on the series' points, when the file says. pub(super) markers: Option, + /// The marker shape (`c:marker/c:symbol`; a circle when missing or unknown) and its size in + /// points (`c:marker/c:size`), when the file gives one. + pub(super) symbol: Symbol, + pub(super) marker_size: Option, /// Draw the series' line as a smooth curve (`c:smooth`). pub(super) smooth: bool, pub(super) values: Vec>, @@ -96,6 +135,8 @@ pub(super) struct Series { pub(super) x_fmt: Option, /// Data labels on or off for this series (`c:dLbls` of its own), when it says. pub(super) labels: Option, + /// The labels' own number format (`c:dLbls/c:numFmt` not linked to the source), if any. + pub(super) label_fmt: Option, /// The values as the file has them, for data labels (`values` become shares in a 100% /// stacked chart); empty when the series shows no labels. pub(super) raw: Vec>, diff --git a/crates/docx/src/read/chart/parse.rs b/crates/docx/src/read/chart/parse.rs index 6b20879c6..ec1508154 100644 --- a/crates/docx/src/read/chart/parse.rs +++ b/crates/docx/src/read/chart/parse.rs @@ -1,5 +1,5 @@ use super::format::{date_text, excel_stamp, format_value, is_date_code}; -use super::model::{Axis, Grouping, Kind, Pos, Series}; +use super::model::{Axis, Grouping, Kind, Pos, Series, Symbol}; use super::plot::label; use super::{Chart, El, FONT, MAX_CELLS, MAX_POINTS, MAX_RADAR_SERIES, MAX_SERIES, MAX_SPOKES, Rgb, fill_colour, int, measure, slot}; @@ -39,10 +39,14 @@ impl Chart { cats.resize(n, String::new()); let radar_style = ty.child("c:radarStyle").and_then(|r| r.attr("val")); let type_labels = show_values(ty.child("c:dLbls")); + let type_fmt = label_format(ty.child("c:dLbls")); for s in &mut series { s.values.resize(n, None); s.xs.resize(n, None); s.labels = Some(s.labels.or(type_labels).unwrap_or(false)); + if s.label_fmt.is_none() { + s.label_fmt.clone_from(&type_fmt); + } if s.labels == Some(true) { s.raw = s.values.clone(); } @@ -180,6 +184,15 @@ fn show_values(d: Option<&El>) -> Option { d.child("c:showVal").map(|v| v.attr("val").is_none_or(truthy)) } +/// The number format of data labels (`c:dLbls/c:numFmt`) when it is not linked to the source. +fn label_format(d: Option<&El>) -> Option { + d?.child("c:numFmt") + .filter(|f| f.attr("sourceLinked") != Some("1")) + .and_then(|f| f.attr("formatCode")) + .filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT) + .map(str::to_string) +} + fn legend_pos(chart: &El) -> Option { chart.child("c:legend").map(|l| match l.child("c:legendPos").and_then(|p| p.attr("val")).unwrap_or("r") { "l" => Pos::Left, @@ -213,7 +226,15 @@ impl Series { // `c:marker/c:symbol`: which symbol each point gets (`none` for no markers). Scatter // series show markers unless the file says not; line series only when it says so. let symbol = ser.child("c:marker").and_then(|m| m.child("c:symbol")).and_then(|s| s.attr("val")).map(str::to_string); - let markers = symbol.map(|s| s != "none").or_else(|| scatter.then_some(true)); + let markers = symbol.as_deref().map(|s| s != "none").or_else(|| scatter.then_some(true)); + let symbol = symbol.as_deref().map_or(Symbol::Circle, Symbol::parse); + let marker_size = ser + .child("c:marker") + .and_then(|m| m.child("c:size")) + .and_then(|s| s.attr("val")) + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| v.is_finite()) + .map(|v| v.clamp(2.0, 72.0)); let smooth = ser.child("c:smooth").and_then(|s| s.attr("val")).is_some_and(truthy); let (values, fmt) = numbers(ser.child(if scatter { "c:yVal" } else { "c:val" }), cap); let (mut xs, x_fmt) = if scatter { numbers(ser.child("c:xVal"), cap) } else { (Vec::new(), None) }; @@ -229,7 +250,27 @@ impl Series { } } let labels = show_values(ser.child("c:dLbls")); - Series { name, idx, color, line_w, line, no_fill, markers, smooth, values, xs, points, fmt, x_fmt, labels, raw: Vec::new() } + let label_fmt = label_format(ser.child("c:dLbls")); + Series { + name, + idx, + color, + line_w, + line, + no_fill, + markers, + symbol, + marker_size, + smooth, + values, + xs, + points, + fmt, + x_fmt, + labels, + label_fmt, + raw: Vec::new(), + } } } @@ -314,6 +355,12 @@ pub(super) fn axis(a: Option<&El>) -> Axis { .filter(|f| f.chars().count() <= craft_wordmodel::chart::MAX_FMT) .map(str::to_string), title: a.child("c:title").and_then(title_text), + title_rot: a + .child("c:title") + .and_then(|t| t.find("a:bodyPr")) + .and_then(|b| b.attr("rot")) + .and_then(|v| v.trim().parse::().ok()) + .map(|v| (v as f64 / 60_000.0).clamp(-360.0, 360.0) as f32), labels: a.child("c:tickLblPos").and_then(|p| p.attr("val")) != Some("none"), } } diff --git a/crates/docx/src/read/chart/plot.rs b/crates/docx/src/read/chart/plot.rs index eae203546..775d24eb2 100644 --- a/crates/docx/src/read/chart/plot.rs +++ b/crates/docx/src/read/chart/plot.rs @@ -1,10 +1,13 @@ use super::canvas::{Rect, clip_text, fill, rect_segs, runs, seg, stroke, text, text_angle, text_at, text_w, widest, wrap}; use super::format::format_value; -use super::model::{DataLabel, Grouping, Kind, Series}; +use super::model::{DataLabel, Grouping, Kind, Series, Symbol}; use super::parse::category_text; use super::polar::{draw_data_labels, label_of}; use super::{AXIS, Chart, El, GAP, GRID, GraphicItem, LINE, LINE_W, MAX_LABEL, MAX_TICKS, PathSeg, Rgb, ShapeKind, TextAlign, fill_colour, measure}; +/// Line width of the stroked marker symbols (x, plus, star), points. +const MARKER_STROKE: f32 = 1.5; + pub(super) fn label(s: &str) -> String { s.chars().take(MAX_LABEL).collect() } @@ -243,18 +246,21 @@ pub(super) fn cartesian(out: &mut Vec, c: &Chart, area: Rect) { } /// The axis titles, one line: the title of the vertical axis (the value axis for columns, the -/// category axis for bars) is rotated 90° on the plot's left; the horizontal axis's title sits +/// category axis for bars) is turned 90° on the plot's left; the horizontal axis's title sits /// under the plot. fn draw_axis_titles(out: &mut Vec, c: &Chart, g: &Frame, area: Rect) { let lh = c.text_size * LINE; // The axis drawn along the plot's left (the value axis for columns, the category axis for // bars) gets its title rotated there; the other axis's title sits under the plot. let (left, bottom) = if c.horizontal { (&c.cat, &c.val) } else { (&c.val, &c.cat) }; + // Word turns the vertical axis's title counter-clockwise (reading upwards) unless the file + // turns it the other way; a title with any other rotation would not fit the strip. + let up = if left.title_rot.is_some_and(|r| (r.rem_euclid(360.0) - 90.0).abs() < 1.0) { 90.0 } else { -90.0 }; if !left.deleted && let Some(t) = &left.title { let t = clip_text(t, g.plot.h, c.text_size); - text_angle(out, Rect { x: area.x, y: g.plot.y, w: lh, h: g.plot.h }, &t, c.text_size, TextAlign::Center, false, 90.0); + text_angle(out, Rect { x: area.x, y: g.plot.y, w: lh, h: g.plot.h }, &t, c.text_size, TextAlign::Center, false, up); } if !bottom.deleted && let Some(t) = &bottom.title @@ -481,18 +487,48 @@ fn lines(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut Vec, pts: impl Iterator, colour: Rgb) { +/// A series' point markers in the series' symbol and size (`colour` fills or strokes them), for +/// lines and scatter charts. +fn markers(out: &mut Vec, pts: impl Iterator, colour: Rgb, s: &Series) { const MARKER: f32 = 6.0; + let size = s.marker_size.filter(|v| v.is_finite()).unwrap_or(MARKER).clamp(2.0, 72.0); + let h = size / 2.0; + let shape = |out: &mut Vec, rect: [f32; 4], kind: ShapeKind| { + out.push(GraphicItem::Shape { rect, kind, fill: Some(colour), stroke: None, stroke_width: 0.0 }); + }; + let mut strokes = Vec::new(); for (x, y) in pts { - let rect = [x - MARKER / 2.0, y - MARKER / 2.0, MARKER, MARKER]; - out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(colour), stroke: None, stroke_width: 0.0 }); + match s.symbol { + Symbol::Circle => shape(out, [x - h, y - h, size, size], ShapeKind::Ellipse), + Symbol::Square => shape(out, [x - h, y - h, size, size], ShapeKind::Rectangle), + Symbol::Dot => shape(out, [x - h / 2.0, y - h / 2.0, h, h], ShapeKind::Ellipse), + Symbol::Dash => shape(out, [x - h, y - size / 6.0, size, size / 3.0], ShapeKind::Rectangle), + Symbol::Diamond => fill( + out, + vec![PathSeg::Move(x, y - h), PathSeg::Line(x + h, y), PathSeg::Line(x, y + h), PathSeg::Line(x - h, y), PathSeg::Close], + colour, + ), + Symbol::Triangle => { + fill(out, vec![PathSeg::Move(x, y - h), PathSeg::Line(x + h, y + h), PathSeg::Line(x - h, y + h), PathSeg::Close], colour) + } + Symbol::X | Symbol::Plus | Symbol::Star => { + if s.symbol != Symbol::Plus { + strokes.extend(seg(x - h, y - h, x + h, y + h)); + strokes.extend(seg(x - h, y + h, x + h, y - h)); + } + if s.symbol != Symbol::X { + strokes.extend(seg(x - h, y, x + h, y)); + strokes.extend(seg(x, y - h, x, y + h)); + } + } + } } + stroke(out, strokes, colour, MARKER_STROKE); } /// A polyline through `pts`, a smooth curve (Catmull-Rom pieces) when `smooth` and there are at @@ -582,10 +618,7 @@ fn draw_scatter(out: &mut Vec, c: &Chart, g: &Frame, labels: &mut V stroke(out, curve(pts.iter().copied(), s.smooth), c.series_colour(j), s.line_w.unwrap_or(LINE_W)); } if s.markers != Some(false) { - for (x, y) in pts.iter().flatten() { - let rect = [x - MARKER / 2.0, y - MARKER / 2.0, MARKER, MARKER]; - out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(c.series_colour(j)), stroke: None, stroke_width: 0.0 }); - } + markers(out, pts.iter().flatten().copied(), c.series_colour(j), s); } } } diff --git a/crates/docx/src/read/chart/polar.rs b/crates/docx/src/read/chart/polar.rs index ec7768d5c..dbbe390db 100644 --- a/crates/docx/src/read/chart/polar.rs +++ b/crates/docx/src/read/chart/polar.rs @@ -134,13 +134,13 @@ pub(super) fn radar(out: &mut Vec, c: &Chart, area: Rect) { } /// The data label of point `i` of series `s`, when it shows one: the value as the file has it, -/// in the series' number format. +/// in the labels' own number format, else the series' one. pub(super) fn label_of(s: &Series, i: usize) -> Option { if s.labels != Some(true) { return None; } let v = s.raw.get(i).copied().flatten()?; - let fmt = s.fmt.as_deref().filter(|f| !f.eq_ignore_ascii_case("General")); + let fmt = s.label_fmt.as_deref().or(s.fmt.as_deref()).filter(|f| !f.eq_ignore_ascii_case("General")); Some(match fmt { Some(f) => format_value(v, f, 1.0), None => general_value(v), diff --git a/crates/docx/src/read/chart/tests.rs b/crates/docx/src/read/chart/tests.rs index 74573b5d8..b156817d2 100644 --- a/crates/docx/src/read/chart/tests.rs +++ b/crates/docx/src/read/chart/tests.rs @@ -656,3 +656,96 @@ fn category_gridlines_follow_the_points_when_the_axis_crosses_mid() { assert!(grid.iter().zip(&pts).all(|(g, p)| (g - p).abs() < 1e-3), "{cross}: grid {grid:?} points {pts:?}"); } } + +/// A line chart with one series; `extra` goes into the series (`c:marker`, `c:dLbls`), `axes` +/// into the value axis. +fn line_with(extra: &str, val_axis: &str) -> Vec { + let s = ser(0, "S", Some("FF0000"), &["Q1", "Q2", "Q3"], &["3.2", "4.1", "5"]).replace("", &format!("{extra}")); + let plot = format!( + r#"{s}{val_axis}"# + ); + chart_items(&space(&plot), &theme(), 300.0, 200.0) +} + +fn marker_xml(symbol: &str, size: u32) -> String { + format!(r#""#) +} + +#[test] +fn marker_symbols_are_drawn_as_their_shape() { + let shapes = |items: &[GraphicItem], kind: ShapeKind| { + items + .iter() + .filter(|it| matches!(it, GraphicItem::Shape { kind: k, rect, .. } if *k == kind && rect[2] > 3.0 && rect[2] < 20.0 && rect[3] > 1.0)) + .count() + }; + let paths = |items: &[GraphicItem], filled: bool| { + items + .iter() + .filter(|it| matches!(it, GraphicItem::Path { fill, segs, .. } if fill.is_some() == filled && segs.len() <= 12 && segs.len() >= 3)) + .count() + }; + // One marker per point, in the series' size. + let circle = line_with(&marker_xml("circle", 9), ""); + assert_eq!(shapes(&circle, ShapeKind::Ellipse), 3); + assert!(circle.iter().any(|it| matches!(it, GraphicItem::Shape { kind: ShapeKind::Ellipse, rect, .. } if (rect[2] - 9.0).abs() < 1e-3))); + let square = line_with(&marker_xml("square", 7), ""); + assert_eq!(shapes(&square, ShapeKind::Rectangle) - shapes(&circle, ShapeKind::Rectangle), 3, "a square per point"); + assert_eq!(shapes(&square, ShapeKind::Ellipse), 0, "no circles"); + // Diamonds and triangles are filled polygons; x, plus and star are strokes. + let base = paths(&line_with("", ""), true); + assert_eq!(paths(&line_with(&marker_xml("diamond", 7), ""), true) - base, 3); + assert_eq!(paths(&line_with(&marker_xml("triangle", 7), ""), true) - base, 3); + for symbol in ["x", "plus", "star"] { + let items = line_with(&marker_xml(symbol, 7), ""); + assert!(items.iter().any(|it| matches!(it, GraphicItem::Path { fill: None, stroke: Some(_), segs, .. } if segs.len() >= 6)), "{symbol}"); + assert_eq!(shapes(&items, ShapeKind::Ellipse), 0, "{symbol} is not a circle"); + } + // Dash and dot are small shapes; `none` and unknown names never crash (unknown: a circle). + assert_eq!(shapes(&line_with(&marker_xml("dash", 7), ""), ShapeKind::Rectangle) - shapes(&circle, ShapeKind::Rectangle), 3); + assert_eq!(shapes(&line_with(&marker_xml("dot", 7), ""), ShapeKind::Ellipse), 3); + assert_eq!(shapes(&line_with(&marker_xml("none", 7), ""), ShapeKind::Ellipse), 0); + assert_eq!(shapes(&line_with(&marker_xml("wibble", 7), ""), ShapeKind::Ellipse), 3); + // Hostile sizes are clamped. + for size in ["0", "99999999999", "-4", "x"] { + let items = line_with(&format!(r#""#), ""); + assert!(items.iter().all(|it| match it { + GraphicItem::Shape { rect, .. } => rect.iter().all(|v| v.is_finite()) && rect[2] <= 300.0, + _ => true, + })); + } +} + +#[test] +fn data_labels_use_their_own_format_code() { + let dl = |num: &str| format!(r#"{num}"#); + let shown = |items: &[GraphicItem]| -> Vec { + items.iter().filter_map(|it| if let GraphicItem::Text { text, .. } = it { Some(text.clone()) } else { None }).collect() + }; + let own = shown(&line_with(&dl(r#""#), "")); + assert!(own.contains(&"3.20".to_string()) && own.contains(&"5.00".to_string()), "{own:?}"); + // Linked to the source: the series' format (General here). + let linked = shown(&line_with(&dl(r#""#), "")); + assert!(linked.contains(&"3.2".to_string()) && linked.contains(&"5".to_string()), "{linked:?}"); + // A format code beyond the cap is ignored, not applied. + let long = "0".repeat(craft_wordmodel::chart::MAX_FMT + 1); + let capped = shown(&line_with(&dl(&format!(r#""#)), "")); + assert!(capped.contains(&"3.2".to_string()), "{capped:?}"); +} + +#[test] +fn value_axis_title_turns_counter_clockwise_like_word() { + let title = |body: &str| format!(r#"{body}Revenue"#); + let angle = |items: &[GraphicItem]| { + items.iter().find_map(|it| if let GraphicItem::Text { text, angle, .. } = it { (text == "Revenue").then_some(*angle) } else { None }) + }; + // The file's rotation (`-5400000` is 90° counter-clockwise), or Word's default when it says none. + assert_eq!(angle(&line_with("", &title(r#""#))), Some(-90.0)); + assert_eq!(angle(&line_with("", &title(""))), Some(-90.0)); + assert_eq!(angle(&line_with("", &title(r#""#))), Some(90.0)); + // A horizontal title has no room beside the plot: it stays turned up. + assert_eq!(angle(&line_with("", &title(r#""#))), Some(-90.0)); + // Hostile values stay finite. + let odd = angle(&line_with("", &title(r#""#))); + assert!(odd.is_some_and(f32::is_finite)); +} diff --git a/crates/wordmodel/src/graphic.rs b/crates/wordmodel/src/graphic.rs index f4a7bcf2e..cba7e766a 100644 --- a/crates/wordmodel/src/graphic.rs +++ b/crates/wordmodel/src/graphic.rs @@ -117,7 +117,7 @@ pub enum GraphicItem { }, /// One line of text in `rect`, aligned horizontally by `align`, centred vertically; `angle` /// degrees clockwise turns the text about `rect`'s centre as it is drawn (chart axis titles - /// use 90° for the vertical axis). + /// turn the vertical axis's title -90°, reading upwards, as Word does). Text { rect: [f32; 4], text: String,