excelerate 0.16.0

Read, write and recalculate spreadsheets: xlsx, xls, ods, csv, html, and a 518-function formula engine
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Writing shapes: an untouched one as the bytes it came in, a changed or new
//! one spliced into its drawing.
//!
//! Runs after [`super::image`], over the drawing parts it left, and in the
//! same way: the shape element is kept and only what the model names in it is
//! rewritten. See [`crate::model::shape`].

use super::chart::{
    DRAWING_NS, DRAWING_TYPE, MAIN_NS, REL_NS, XML_DECL, drawings, max_object_id, part_text,
    render_anchor, set_part,
};
use super::chart::{fill_xml, rebuild, set_attr, shape_format};
use super::image::{free_path, reanchor, rename, set_attribute, splice};
use super::xmlesc::escape;
use crate::model::chart::{ChartColor, Fill, ShapeFormat};
use crate::model::shape::Shape;
use crate::model::{Attachment, Spreadsheet, Worksheet};
use crate::reader::chart::{FILLS, Node, children};
use crate::reader::shape::{ShapeObject, child_element, scan_shapes};
use crate::style::DiffFont;
use core::ops::Range;
use std::borrow::Cow;

/// The workbook as the writer should see it, shapes applied.
pub(super) fn prepare(book: Cow<'_, Spreadsheet>) -> Cow<'_, Spreadsheet> {
    let dirty: Vec<usize> = book
        .sheets()
        .iter()
        .enumerate()
        .filter(|(_, sheet)| {
            sheet.shapes.iter().any(|s| !s.is_unchanged())
                || drawings(sheet).any(|d| lost_shapes(&book, sheet, d))
        })
        .map(|(i, _)| i)
        .collect();
    if dirty.is_empty() {
        return book;
    }
    let mut book = book.into_owned();
    for index in dirty {
        apply_sheet(&mut book, index);
    }
    Cow::Owned(book)
}

/// Whether a drawing holds a shape the sheet no longer has.
fn lost_shapes(book: &Spreadsheet, sheet: &Worksheet, drawing: &str) -> bool {
    let mut from_here = sheet
        .shapes
        .iter()
        .filter_map(|s| s.origin.as_ref())
        .filter(|o| o.drawing == drawing)
        .peekable();
    // What the reader counted answers without parsing, as long as a shape of
    // this drawing is left to carry the count.
    if let Some(read) = from_here.peek().map(|o| o.read_from_drawing) {
        return from_here.count() < read;
    }
    let Some(xml) = part_text(book, drawing) else {
        return false;
    };
    if !xml.contains(":sp ") && !xml.contains(":sp>") && !xml.contains("<sp") {
        return false;
    }
    scan_shapes(xml, None)
        .iter()
        .filter(|o| o.anchor.is_some())
        .flat_map(|o| &o.shapes)
        .any(|s| claimant(&sheet.shapes, drawing, s.id).is_none())
}

fn claimant(shapes: &[Shape], drawing: &str, id: u32) -> Option<usize> {
    shapes.iter().position(|s| {
        s.origin
            .as_ref()
            .is_some_and(|o| o.drawing == drawing && o.id == id)
    })
}

fn apply_sheet(book: &mut Spreadsheet, index: usize) {
    let Some(sheet) = book.sheet(index) else {
        return;
    };
    let shapes = sheet.shapes.clone();
    let mut paths: Vec<String> = drawings(sheet).map(str::to_owned).collect();
    if paths.is_empty() {
        if shapes.iter().all(|s| s.origin.is_some()) {
            return;
        }
        let path = free_path(book, "xl/drawings/drawing", "xml");
        let empty = format!(
            r#"{XML_DECL}<xdr:wsDr xmlns:xdr="{DRAWING_NS}" xmlns:a="{MAIN_NS}"></xdr:wsDr>"#
        );
        set_part(book, &path, Some(DRAWING_TYPE), empty);
        if let Some(sheet) = book.sheet_mut(index) {
            sheet.attachments.push(Attachment {
                kind: format!("{REL_NS}/drawing"),
                target: path.clone(),
            });
        }
        paths.push(path);
    }
    // The first drawing takes the new shapes.
    for (i, path) in paths.iter().enumerate() {
        rewrite_drawing(book, path, &shapes, i == 0);
    }
}

fn rewrite_drawing(book: &mut Spreadsheet, path: &str, shapes: &[Shape], takes_new: bool) {
    let Some(xml) = part_text(book, path).map(str::to_owned) else {
        return;
    };
    let mut splices: Vec<(Range<usize>, String)> = scan_shapes(&xml, None)
        .iter()
        // An object without an anchor the reader understood never reached
        // the model, so it is not the model's to change.
        .filter(|o| o.anchor.is_some())
        .filter_map(|o| rewrite_object(&xml, o, path, shapes).map(|t| (o.span.clone(), t)))
        .collect();
    if takes_new {
        let mut next_id = max_object_id(&xml);
        let mut objects = String::new();
        for shape in shapes.iter().filter(|s| s.origin.is_none()) {
            next_id = next_id.saturating_add(1);
            objects.push_str(&render_anchor(shape.anchor, &render_shape(shape, next_id)));
        }
        if !objects.is_empty() {
            let close = xml.rfind("</").unwrap_or(xml.len());
            splices.push((close..close, objects));
        }
    }
    if !splices.is_empty() {
        set_part(book, path, Some(DRAWING_TYPE), splice(&xml, splices));
    }
}

/// The new text of one anchored object, or `None` when it stays as it is. An
/// empty text removes the object.
fn rewrite_object(
    xml: &str,
    object: &ShapeObject,
    drawing: &str,
    shapes: &[Shape],
) -> Option<String> {
    let base = object.span.start;
    let original = &xml[object.span.clone()];
    let alone = matches!(object.shapes.as_slice(), [s] if !s.grouped);
    let mut splices: Vec<(Range<usize>, String)> = Vec::new();
    let mut moved_to = None;

    for element in &object.shapes {
        let local = element.span.start - base..element.span.end - base;
        let Some(index) = claimant(shapes, drawing, element.id) else {
            if alone {
                return Some(String::new());
            }
            splices.push((local, String::new()));
            continue;
        };
        let shape = &shapes[index];
        let Some(origin) = &shape.origin else {
            continue;
        };
        let mut text = original[local.clone()].to_owned();
        // The fill and outline first: they are rebuilt from the properties
        // as read, which the outline and the turn below then edit.
        if shape.format != origin.format {
            text = reformat(&text, &shape.format, &origin.format);
        }
        if shape.name != origin.name || shape.description != origin.description {
            text = rename(&text, &shape.name, &shape.description);
        }
        if shape.geometry != origin.geometry
            && let Some(geometry) = &shape.geometry
        {
            text = regeometry(&text, geometry);
        }
        if (shape.rotation, shape.flip_h, shape.flip_v)
            != (origin.rotation, origin.flip_h, origin.flip_v)
        {
            text = retransform(&text, shape);
        }
        if shape.text != origin.text || shape.font != origin.font {
            let font = (shape.font != origin.font).then_some((&shape.font, &origin.font));
            text = retext(&text, &shape.text, font);
        }
        if text != original[local.clone()] {
            splices.push((local, text));
        }
        // A shape inside a group is placed by the group.
        if alone && shape.anchor != origin.anchor {
            moved_to = Some(shape.anchor);
        }
    }
    if splices.is_empty() && moved_to.is_none() {
        return None;
    }
    let text = splice(original, splices);
    Some(match moved_to {
        Some(anchor) => reanchor(&text, anchor),
        None => text,
    })
}

/// A shape element with its fill and outline from the model: the children of
/// `spPr` that say them are replaced and the rest kept.
fn reformat(element: &str, format: &ShapeFormat, read: &ShapeFormat) -> String {
    let Some(properties) = child_element(element, "spPr") else {
        return element.to_owned();
    };
    let start = properties.as_ptr() as usize - element.as_ptr() as usize;
    // A format without the element as read is rebuilt into the one that was:
    // written alone it would lose the frame and the outline.
    let mut format = format.clone();
    if format.source.is_none() {
        format.source.clone_from(&read.source);
    }
    if format.source.is_none() {
        return element.to_owned();
    }
    format!(
        "{}{}{}",
        &element[..start],
        shape_format("", &format),
        &element[start + properties.len()..]
    )
}

/// A shape element turned and mirrored as the model says: attributes of
/// `a:xfrm`, which is added when the element has none.
fn retransform(element: &str, shape: &Shape) -> String {
    let Some(properties) = child_element(element, "spPr") else {
        return element.to_owned();
    };
    let base = properties.as_ptr() as usize - element.as_ptr() as usize;
    if let Some(tag) = crate::reader::shape::start_tag(properties, "xfrm") {
        let start = base + (tag.as_ptr() as usize - properties.as_ptr() as usize);
        let end = start + tag.trim_end_matches('>').len();
        let mut tag = element[start..end].to_owned();
        for (name, value) in transform_attributes(shape) {
            tag = set_attribute(&tag, name, &value);
        }
        return format!("{}{tag}{}", &element[..start], &element[end..]);
    }
    let Some(open) = properties
        .find('>')
        .filter(|&gt| !properties[..gt].ends_with('/'))
    else {
        return element.to_owned();
    };
    let at = base + open + 1;
    let mut tag = "<a:xfrm/".to_owned();
    for (name, value) in transform_attributes(shape) {
        tag = set_attribute(&tag, name, &value);
    }
    format!("{}{tag}>{}", &element[..at], &element[at..])
}

/// `rot`, `flipH` and `flipV` of `a:xfrm`, all three: a turn back to none is
/// written as `0`, not dropped.
fn transform_attributes(shape: &Shape) -> [(&'static str, String); 3] {
    let flag = |on: bool| if on { "1" } else { "0" }.to_owned();
    [
        ("rot", shape.rotation.to_string()),
        ("flipH", flag(shape.flip_h)),
        ("flipV", flag(shape.flip_v)),
    ]
}

/// A shape element with another preset outline.
///
/// ponytail: a freeform outline (`custGeom`) is left as it is; turning it into
/// a preset means replacing the element, not an attribute.
fn regeometry(element: &str, geometry: &str) -> String {
    let Some(start) = element.find("prstGeom ") else {
        return element.to_owned();
    };
    let Some(end) = element[start..].find('>').map(|e| start + e) else {
        return element.to_owned();
    };
    let tag = set_attribute(&element[start..end], "prst", geometry);
    format!("{}{tag}{}", &element[..start], &element[end..])
}

/// A shape element with its text replaced. The body's own properties, the
/// first paragraph's properties and the first run's formatting are kept, so
/// the new text looks like the old; a shape that had no text gets a body.
/// `font` is a new font with the one read, which every run takes.
fn retext(element: &str, text: &str, font: Option<(&DiffFont, &DiffFont)>) -> String {
    let Some(sp) = children(element).into_iter().next() else {
        return element.to_owned();
    };
    let own = if sp.prefix.is_empty() {
        String::new()
    } else {
        format!("{}:", sp.prefix)
    };
    let Some(body) = sp.child("txBody") else {
        let at = sp.inner_start + sp.inner.len();
        let run = font.map_or_else(String::new, |(new, was)| run_props(None, new, was, "a:"));
        let fresh = format!(
            r#"<{own}txBody><a:bodyPr rtlCol="0" anchor="ctr"/><a:lstStyle/>{}</{own}txBody>"#,
            paragraphs(text, "a:", "", &run)
        );
        return format!("{}{fresh}{}", &element[..at], &element[at..]);
    };
    let kids = body.children();
    let keep: String = kids
        .iter()
        .filter(|k| matches!(k.name, "bodyPr" | "lstStyle"))
        .map(|k| k.outer)
        .collect();
    let first = kids.iter().find(|k| k.name == "p");
    let a = kids
        .first()
        .filter(|k| !k.prefix.is_empty())
        .map_or_else(|| "a:".to_owned(), |k| format!("{}:", k.prefix));
    let paragraph_props = first.and_then(|p| p.child("pPr")).map_or("", |n| n.outer);
    let read = kids
        .iter()
        .filter(|k| k.name == "p")
        .flat_map(Node::children)
        .find_map(|r| r.child("rPr").filter(|_| r.name == "r"));
    let run_props = match font {
        Some((new, was)) => run_props(read.as_ref(), new, was, &a),
        None => read.map_or_else(String::new, |n| n.outer.to_owned()),
    };
    let start = sp.inner_start + body.inner_start;
    let end = start + body.inner.len();
    format!(
        "{}{keep}{}{}",
        &element[..start],
        paragraphs(text, &a, paragraph_props, &run_props),
        &element[end..]
    )
}

/// Children of `a:rPr`, in schema order.
const RUN: &[&[&str]] = &[
    &["ln"],
    &FILLS,
    &["effectLst", "effectDag"],
    &["highlight"],
    &["uLnTx", "uLn"],
    &["uFillTx", "uFill"],
    &["latin"],
    &["ea"],
    &["cs"],
    &["sym"],
    &["hlinkClick"],
    &["hlinkMouseOver"],
    &["rtl"],
    &["extLst"],
];

/// `a:rPr` with the font the model gives: `read` edited, or a new one. Size,
/// bold and italic are attributes, set or dropped; the colour and the family
/// are children, replaced only when they changed from `was`, so a colour the
/// model reads approximately is not rewritten for a change of size.
fn run_props(read: Option<&Node<'_>>, font: &DiffFont, was: &DiffFont, a: &str) -> String {
    let fresh = format!("<{a}rPr/>");
    let parsed = children(&fresh);
    let Some(node) = read.or_else(|| parsed.first()) else {
        return String::new();
    };
    let flag = |on: Option<bool>| on.map(|b| if b { "1" } else { "0" }.to_owned());
    let mut tag = node.tag.to_owned();
    for (name, value) in [
        ("sz", font.size.map(|v| v.to_string())),
        ("b", flag(font.bold)),
        ("i", flag(font.italic)),
    ] {
        tag = set_attr(&tag, name, value);
    }
    let mut owned = Vec::new();
    if font.color != was.color {
        let fill = font
            .color
            .as_ref()
            .and_then(ChartColor::from_style)
            .map_or_else(String::new, |c| fill_xml(&Fill::Solid(c)));
        owned.push((1, fill));
    }
    if font.name != was.name {
        let latin = font.name.as_ref().map_or_else(String::new, |n| {
            format!(r#"<a:latin xmlns:a="{MAIN_NS}" typeface="{}"/>"#, escape(n))
        });
        owned.push((6, latin));
    }
    rebuild(node, RUN, &owned, |_| false, Some(tag))
}

/// Paragraphs of `DrawingML` text, a paragraph per line.
fn paragraphs(text: &str, a: &str, paragraph_props: &str, run_props: &str) -> String {
    text.split('\n')
        .map(|line| {
            let line = line.strip_suffix('\r').unwrap_or(line);
            if line.is_empty() {
                format!("<{a}p>{paragraph_props}</{a}p>")
            } else {
                format!(
                    "<{a}p>{paragraph_props}<{a}r>{run_props}<{a}t>{}</{a}t></{a}r></{a}p>",
                    escape(line)
                )
            }
        })
        .collect()
}

/// A shape element for a shape made in code, drawn the way Excel draws a new
/// one: the theme's first accent colour with a darker outline and light text.
fn render_shape(shape: &Shape, id: u32) -> String {
    let name = if shape.name.is_empty() {
        format!("Shape {id}")
    } else {
        shape.name.clone()
    };
    let geometry = shape.geometry.as_deref().unwrap_or("rect");
    let body = if shape.text.is_empty() {
        String::new()
    } else {
        let run = if shape.font == DiffFont::default() {
            String::new()
        } else {
            run_props(None, &shape.font, &DiffFont::default(), "a:")
        };
        format!(
            r#"<xdr:txBody><a:bodyPr vertOverflow="clip" horzOverflow="clip" rtlCol="0" anchor="ctr"/><a:lstStyle/>{}</xdr:txBody>"#,
            paragraphs(&shape.text, "a:", r#"<a:pPr algn="ctr"/>"#, &run)
        )
    };
    let mut transform = String::new();
    if shape.rotation != 0 {
        transform = format!(r#" rot="{}""#, shape.rotation);
    }
    if shape.flip_h {
        transform.push_str(r#" flipH="1""#);
    }
    if shape.flip_v {
        transform.push_str(r#" flipV="1""#);
    }
    // The fill and outline go into the properties the way a change to a read
    // shape does, in schema order after the outline.
    let properties = shape_format(
        "",
        &ShapeFormat {
            source: Some(format!(
                concat!(
                    r#"<xdr:spPr><a:xfrm{}><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></a:xfrm>"#,
                    r#"<a:prstGeom prst="{}"><a:avLst/></a:prstGeom></xdr:spPr>"#
                ),
                transform,
                escape(geometry)
            )),
            ..shape.format.clone()
        },
    );
    format!(
        concat!(
            r#"<xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="{id}" name="{name}" descr="{descr}"/>"#,
            r#"<xdr:cNvSpPr/></xdr:nvSpPr>{properties}"#,
            r#"<xdr:style><a:lnRef idx="2"><a:schemeClr val="accent1"><a:shade val="50000"/></a:schemeClr></a:lnRef>"#,
            r#"<a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>"#,
            r#"<a:effectRef idx="0"><a:schemeClr val="accent1"/></a:effectRef>"#,
            r#"<a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></xdr:style>"#,
            r#"{body}</xdr:sp><xdr:clientData/>"#
        ),
        id = id,
        name = escape(&name),
        descr = escape(&shape.description),
        properties = properties,
        body = body,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    const SHAPE: &str = concat!(
        r#"<xdr:sp macro=""><xdr:nvSpPr><xdr:cNvPr id="2" name="Box"/><xdr:cNvSpPr/></xdr:nvSpPr>"#,
        r#"<xdr:spPr><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></xdr:spPr>"#,
        r#"<xdr:txBody><a:bodyPr anchor="t"/><a:lstStyle/><a:p><a:pPr algn="l"/>"#,
        r#"<a:r><a:rPr lang="ru-RU" b="1"/><a:t>old</a:t></a:r></a:p></xdr:txBody></xdr:sp>"#,
    );

    #[test]
    fn new_text_keeps_the_formatting_of_the_old() {
        let out = retext(SHAPE, "one & two\n\nthree", None);
        assert!(out.contains(r#"<a:bodyPr anchor="t"/><a:lstStyle/>"#));
        assert!(out.contains(
            r#"<a:p><a:pPr algn="l"/><a:r><a:rPr lang="ru-RU" b="1"/><a:t>one &amp; two</a:t></a:r></a:p>"#
        ));
        assert!(out.contains(r#"<a:p><a:pPr algn="l"/></a:p>"#));
        assert!(!out.contains("old"));
        let body = children(&out)[0].child("txBody").unwrap();
        assert_eq!(
            crate::reader::shape::body_text(body.outer),
            "one & two\n\nthree"
        );
    }

    #[test]
    fn a_shape_without_text_gets_a_body_and_geometry_is_an_attribute() {
        let bare = SHAPE.replace(
            &SHAPE[SHAPE.find("<xdr:txBody>").unwrap()..SHAPE.find("</xdr:sp>").unwrap()],
            "",
        );
        let out = retext(&bare, "hi", None);
        assert!(out.ends_with("<a:t>hi</a:t></a:r></a:p></xdr:txBody></xdr:sp>"));
        assert!(regeometry(SHAPE, "ellipse").contains(r#"<a:prstGeom prst="ellipse">"#));
    }

    #[test]
    fn a_turn_adds_the_transform_an_element_lacks() {
        let mut shape = Shape::new(
            "rect",
            crate::model::chart::Anchor::Absolute {
                x: 0,
                y: 0,
                width: 1,
                height: 1,
            },
        );
        shape.rotation = 60_000;
        shape.flip_h = true;
        let out = retransform(SHAPE, &shape);
        assert!(out.contains(
            r#"<xdr:spPr><a:xfrm rot="60000" flipH="1" flipV="0"/><a:prstGeom prst="rect">"#
        ));
    }
}