rust-office-charts 0.1.7

Render Office Open XML charts to SVG from native Rust or WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use super::chart_colors::color;
use super::util::escape_xml_text;
use super::ThemeColorMap;
use roxmltree::Node;
use rust_office_art::{PictureContext, ResolvedColor, StyleReferenceKind};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Write;

pub(super) const MAIN: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
pub(super) const REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";

pub(super) struct Context<'a> {
    pub theme: &'a ThemeColorMap,
    pub images: Option<&'a HashMap<String, String>>,
    pub theme_xml: Option<&'a str>,
    pub theme_override: Option<&'a str>,
}

impl PictureContext for Context<'_> {
    fn resolve_color(&self, xml: &str) -> Option<ResolvedColor> {
        let wrapped = format!(r#"<root xmlns:a="{MAIN}">{xml}</root>"#);
        let document = roxmltree::Document::parse(&wrapped).ok()?;
        let value = document
            .descendants()
            .find_map(|node| color(node, self.theme))?;
        let opacity = value
            .get(7..9)
            .and_then(|s| u8::from_str_radix(s, 16).ok())
            .map(|a| f64::from(a) / 255.0);
        Some(ResolvedColor {
            color: value.get(..7)?.to_owned(),
            opacity,
        })
    }

    fn resolve_image(&self, id: &str) -> Option<String> {
        safe_image(self.images?.get(id)?)
    }

    fn resolve_style_reference(
        &self,
        kind: StyleReferenceKind,
        index: u32,
        placeholder: &str,
    ) -> Option<String> {
        let (list, ordinal) = match kind {
            StyleReferenceKind::Fill if index >= 1001 => ("bgFillStyleLst", index - 1001),
            StyleReferenceKind::Fill => ("fillStyleLst", index.checked_sub(1)?),
            StyleReferenceKind::Line => ("lnStyleLst", index.checked_sub(1)?),
            StyleReferenceKind::Effect => ("effectStyleLst", index.checked_sub(1)?),
        };
        let resolve = |xml: &str| {
            let doc = roxmltree::Document::parse(xml).ok()?;
            let node = doc
                .descendants()
                .find(|n| n.is_element() && n.tag_name().name() == list)?
                .children()
                .filter(Node::is_element)
                .nth(ordinal as usize)?;
            let node = if kind == StyleReferenceKind::Effect {
                child(node, "effectLst").or_else(|| child(node, "effectDag"))?
            } else {
                node
            };
            let mut xml = canonical(node);
            if let Some(value) = self.resolve_color(placeholder) {
                let alpha = value.opacity.unwrap_or(1.0) * 100_000.0;
                let replacement = format!(
                    r#"<a:srgbClr val="{}"><a:alpha val="{alpha:.0}"/></a:srgbClr>"#,
                    &value.color[1..]
                );
                let doc = roxmltree::Document::parse(&xml).ok()?;
                let mut edits: Vec<_> = doc
                    .descendants()
                    .filter(|n| {
                        n.tag_name().name() == "schemeClr" && n.attribute("val") == Some("phClr")
                    })
                    .map(|n| {
                        let transforms = n
                            .children()
                            .filter(Node::is_element)
                            .map(canonical)
                            .collect::<String>();
                        (
                            n.range(),
                            replacement
                                .replace("</a:srgbClr>", &format!("{transforms}</a:srgbClr>")),
                        )
                    })
                    .collect();
                edits.sort_by_key(|(r, _)| r.start);
                for (range, value) in edits.into_iter().rev() {
                    xml.replace_range(range, &value);
                }
            }
            Some(xml)
        };
        self.theme_override
            .and_then(resolve)
            .or_else(|| self.theme_xml.and_then(resolve))
    }
}

pub(super) fn child<'a, 'input>(node: Node<'a, 'input>, name: &str) -> Option<Node<'a, 'input>> {
    node.children()
        .find(|n| n.is_element() && n.tag_name().name() == name)
}

pub(super) fn safe_image(source: &str) -> Option<String> {
    let (header, data) = source.split_once(',')?;
    if source.len() > 96 * 1024 * 1024
        || data.is_empty()
        || data.len() % 4 != 0
        || !matches!(
            header,
            "data:image/png;base64"
                | "data:image/jpeg;base64"
                | "data:image/gif;base64"
                | "data:image/webp;base64"
                | "data:image/bmp;base64"
                | "data:image/tiff;base64"
                | "data:image/x-tiff;base64"
        )
        || data
            .trim_end_matches('=')
            .bytes()
            .any(|c| !c.is_ascii_alphanumeric() && !matches!(c, b'+' | b'/'))
        || data.len() - data.trim_end_matches('=').len() > 2
    {
        return None;
    }
    if matches!(
        header,
        "data:image/bmp;base64" | "data:image/tiff;base64" | "data:image/x-tiff;base64"
    ) {
        rust_office_art::normalize_raster(source)
    } else {
        Some(source.to_owned())
    }
}

pub(super) fn canonical(node: Node) -> String {
    let mut namespaces = BTreeMap::new();
    for element in node.descendants().filter(Node::is_element) {
        for uri in element
            .tag_name()
            .namespace()
            .into_iter()
            .chain(element.attributes().filter_map(|a| a.namespace()))
        {
            let prefix = match uri {
                MAIN | "http://purl.oclc.org/ooxml/drawingml/main" => "a".into(),
                REL | "http://purl.oclc.org/ooxml/officeDocument/relationships" => "r".into(),
                "http://www.w3.org/XML/1998/namespace" => "xml".into(),
                _ => format!("ns{}", namespaces.len()),
            };
            namespaces.entry(uri).or_insert(prefix);
        }
    }
    fn write_node(node: Node, namespaces: &BTreeMap<&str, String>, root: bool, out: &mut String) {
        if node.is_text() {
            out.push_str(&escape_xml_text(node.text().unwrap_or_default()));
            return;
        }
        if !node.is_element() {
            return;
        }
        let name = |local: &str, uri: Option<&str>| {
            uri.and_then(|uri| namespaces.get(uri))
                .map_or_else(|| local.to_owned(), |prefix| format!("{prefix}:{local}"))
        };
        let tag = name(node.tag_name().name(), node.tag_name().namespace());
        write!(out, "<{tag}").unwrap();
        if root {
            for (uri, prefix) in namespaces {
                if prefix != "xml" {
                    write!(out, r#" xmlns:{prefix}="{}""#, escape_xml_text(uri)).unwrap();
                }
            }
        }
        for attr in node.attributes() {
            write!(
                out,
                r#" {}="{}""#,
                name(attr.name(), attr.namespace()),
                escape_xml_text(attr.value())
            )
            .unwrap();
        }
        out.push('>');
        for child in node.children() {
            write_node(child, namespaces, false, out);
        }
        write!(out, "</{tag}>").unwrap();
    }
    let mut out = String::new();
    write_node(node, &namespaces, true, &mut out);
    out
}

pub(super) fn scoped_svg(svg: &str, prefix: &str) -> Option<String> {
    let doc = roxmltree::Document::parse(svg).ok()?;
    let ids: HashSet<_> = doc
        .descendants()
        .filter_map(|n| n.attribute("id"))
        .collect();
    let mut edits = Vec::new();
    for node in doc.descendants().filter(Node::is_element) {
        for attr in node.attributes() {
            let value = attr.value();
            let new = if attr.name() == "id" {
                Some(format!("{prefix}{value}"))
            } else if let Some(id) = value.strip_prefix('#').filter(|id| ids.contains(id)) {
                (attr.name() == "href").then(|| format!("#{prefix}{id}"))
            } else {
                value
                    .strip_prefix("url(#")
                    .and_then(|v| v.strip_suffix(')'))
                    .filter(|id| ids.contains(id))
                    .map(|id| format!("url(#{prefix}{id})"))
            };
            if let Some(value) = new {
                edits.push((attr.range_value(), value));
            }
        }
    }
    edits.sort_by_key(|(r, _)| r.start);
    let mut out = svg.to_owned();
    for (range, value) in edits.into_iter().rev() {
        out.replace_range(range, &value);
    }
    Some(
        out.replace("data-office-art-effect=", "data-chart-effect=")
            .replace("data-office-art-overflow=", "data-chart-overflow=")
            .replace("xlink:href=", "href="),
    )
}

pub(super) fn inner_svg(svg: &str) -> Option<&str> {
    Some(&svg[svg.find('>')? + 1..svg.rfind("</svg>")?])
}

pub(super) fn expand_effects(mut svg: String) -> String {
    if !svg.contains("data-chart-overflow=") {
        return svg;
    }
    let Ok(doc) = roxmltree::Document::parse(&svg) else {
        return svg;
    };
    let mut edits = Vec::new();
    let mut insertions = BTreeMap::<usize, String>::new();
    for node in doc
        .descendants()
        .filter(|n| n.attribute("data-chart-overflow") == Some("true"))
    {
        if node.ancestors().any(|n| n.tag_name().name() == "defs") {
            continue;
        }
        let Some(clip) = node
            .ancestors()
            .filter(|n| n.attribute("clip-path").is_some())
            .last()
        else {
            continue;
        };
        let mut ancestors: Vec<_> = node
            .ancestors()
            .skip(1)
            .take_while(|n| n.id() != clip.id())
            .collect();
        ancestors.push(clip);
        let mut body = String::from(r#"<g data-chart-effect="true" pointer-events="none">"#);
        for parent in ancestors.iter().rev() {
            body.push_str("<g");
            for name in [
                "transform",
                "fill",
                "stroke",
                "stroke-width",
                "opacity",
                "fill-opacity",
                "stroke-opacity",
            ] {
                if let Some(value) = parent.attribute(name) {
                    write!(body, r#" {name}="{}""#, escape_xml_text(value)).unwrap();
                }
            }
            body.push('>');
        }
        body.push_str(&svg[node.range()]);
        for _ in &ancestors {
            body.push_str("</g>");
        }
        body.push_str("</g>");
        insertions
            .entry(clip.range().end)
            .or_default()
            .push_str(&body);
        edits.push((node.range(), String::new()));
    }
    edits.extend(insertions.into_iter().map(|(at, value)| (at..at, value)));
    edits.sort_by_key(|(range, _)| range.start);
    for (range, value) in edits.into_iter().rev() {
        svg.replace_range(range, &value);
    }
    svg.replace(" data-chart-overflow=\"true\"", "")
}

pub(super) fn picture(
    fill: Node,
    properties: Option<Node>,
    source: &str,
    width: f64,
    height: f64,
    context: &Context,
) -> Option<rust_office_art::RenderedPicture> {
    let fill_xml = canonical(fill);
    let contents = &fill_xml[fill_xml.find('>')? + 1..fill_xml.rfind("</")?];
    let rectangular = properties
        .and_then(|p| child(p, "prstGeom"))
        .is_some_and(|g| g.attribute("prst") == Some("rect"));
    let props = properties
        .map(|p| {
            p.children()
                .filter(Node::is_element)
                .filter(|n| !(rectangular && n.tag_name().name() == "prstGeom"))
                .map(canonical)
                .collect::<String>()
        })
        .unwrap_or_default();
    let mut attrs = String::new();
    for name in ["dpi", "rotWithShape"] {
        if let Some(value) = fill.attribute(name) {
            write!(attrs, r#" {name}="{}""#, escape_xml_text(value)).unwrap();
        }
    }
    let geometry = if properties.is_some_and(|p| {
        (!rectangular && child(p, "prstGeom").is_some()) || child(p, "custGeom").is_some()
    }) {
        ""
    } else {
        r#"<a:custGeom><a:pathLst><a:path w="1" h="1"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="1" y="0"/></a:lnTo><a:lnTo><a:pt x="1" y="1"/></a:lnTo><a:lnTo><a:pt x="0" y="1"/></a:lnTo><a:close/></a:path></a:pathLst></a:custGeom>"#
    };
    let xml = format!("<pic:pic><pic:blipFill{attrs}>{contents}</pic:blipFill><pic:spPr>{props}{geometry}</pic:spPr></pic:pic>");
    rust_office_art::render_picture(&xml, source, width, height, context)
}

pub(super) fn geometry_bounds(node: Node, viewport: [f64; 2]) -> Option<[f64; 4]> {
    use kurbo::{BezPath, Shape};
    let num = |name: &str, default: f64| {
        node.attribute(name)
            .and_then(|v| v.parse::<f64>().ok())
            .unwrap_or(default)
    };
    let dimension = |name: &str, extent: f64| {
        node.attribute(name).and_then(|v| {
            v.strip_suffix('%')
                .and_then(|s| s.parse::<f64>().ok())
                .map(|v| v * extent / 100.0)
                .or_else(|| v.parse().ok())
        })
    };
    let bounds = match node.tag_name().name() {
        "rect" | "image" => [
            num("x", 0.0),
            num("y", 0.0),
            dimension("width", viewport[0])?,
            dimension("height", viewport[1])?,
        ],
        "circle" | "ellipse" => {
            let rx = num("rx", num("r", 0.0));
            let ry = num("ry", num("r", 0.0));
            [num("cx", 0.0) - rx, num("cy", 0.0) - ry, rx * 2.0, ry * 2.0]
        }
        "path" | "polygon" | "polyline" | "line" => {
            let mut path = BezPath::new();
            if node.tag_name().name() == "path" {
                for segment in svgtypes::SimplifyingPathParser::from(node.attribute("d")?) {
                    use svgtypes::SimplePathSegment::*;
                    match segment.ok()? {
                        MoveTo { x, y } => path.move_to((x, y)),
                        LineTo { x, y } => path.line_to((x, y)),
                        CurveTo {
                            x1,
                            y1,
                            x2,
                            y2,
                            x,
                            y,
                        } => path.curve_to((x1, y1), (x2, y2), (x, y)),
                        Quadratic { x1, y1, x, y } => path.quad_to((x1, y1), (x, y)),
                        ClosePath => path.close_path(),
                    }
                }
            } else if node.tag_name().name() == "line" {
                path.move_to((num("x1", 0.0), num("y1", 0.0)));
                path.line_to((num("x2", 0.0), num("y2", 0.0)));
            } else {
                for (i, (x, y)) in
                    svgtypes::PointsParser::from(node.attribute("points")?).enumerate()
                {
                    if i == 0 {
                        path.move_to((x, y));
                    } else {
                        path.line_to((x, y));
                    }
                }
            }
            let b = path.bounding_box();
            [b.x0, b.y0, b.width(), b.height()]
        }
        _ => return None,
    };
    (bounds.into_iter().all(f64::is_finite) && bounds[2] > 0.0 && bounds[3] > 0.0).then_some(bounds)
}