f-office-docx 0.2.3

DOCX model and Word's layout rules.
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
//! Tests of the named edits set-text of a paragraph or a cell, the new row, the comment and the
//! image, with the other parts that a comment and an image change and add.

use f_office_paint::ImageFormat;
use f_office_units::Length;

use super::super::{ImageFile, NamedEdit, NamedFault, Place};
use super::{File, at, p, part_text, style_at, texts};

fn set_text(address: &str, text: &str) -> NamedEdit {
    NamedEdit::SetText {
        at: at(address),
        text: text.to_owned(),
    }
}

fn row(address: &str, place: Place, cells: &[&str]) -> NamedEdit {
    NamedEdit::InsertRow {
        at: at(address),
        place,
        cells: cells.iter().map(|&cell| cell.to_owned()).collect(),
    }
}

fn comment(address: &str, find: Option<&str>) -> NamedEdit {
    NamedEdit::Comment {
        at: at(address),
        text: "Check this.".to_owned(),
        find: find.map(str::to_owned),
        author: "Ann".to_owned(),
    }
}

/// An inch, in a length.
fn inches(count: i64) -> Length {
    Length::from_emus(count * 914_400).unwrap()
}

/// An image edit of a PNG file of `width` by `height` inches at its resolution, with the size
/// `size` of its drawing.
fn image(address: &str, own: (i64, i64), size: (Option<Length>, Option<Length>)) -> NamedEdit {
    NamedEdit::InsertImage {
        at: at(address),
        place: Place::After,
        image: ImageFile::new(
            ImageFormat::Png,
            b"\x89PNG\r\n\x1a\nbytes".to_vec(),
            (inches(own.0), inches(own.1)),
        )
        .unwrap(),
        alt: "A chart".to_owned(),
        size,
    }
}

/// A table of the rows `rows`, with a grid of `columns` columns, and a paragraph after it.
fn table(columns: usize, rows: &[String]) -> String {
    let grid = r#"<w:gridCol w:w="2000"/>"#.repeat(columns);
    format!(
        "<w:tbl><w:tblPr/><w:tblGrid>{grid}</w:tblGrid>{}</w:tbl>{}",
        rows.concat(),
        p("end")
    )
}

/// A cell with `properties` in its `w:tcPr` and one paragraph of `text`.
fn cell(properties: &str, text: &str) -> String {
    format!("<w:tc><w:tcPr>{properties}</w:tcPr>{}</w:tc>", p(text))
}

#[test]
fn sets_the_text_of_a_paragraph_in_the_formatting_of_its_first_run() {
    let body = r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">Old </w:t></w:r><w:r><w:t>text</w:t></w:r></w:p>"#;
    let file = File::new(body);
    let (xml, blocks) = file.edited(&[set_text("p1", "New\ttext")]);
    assert!(
        xml.contains(r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>New</w:t><w:tab/><w:t>text</w:t></w:r></w:p>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["New\ttext"]);
    let (xml, blocks) = file.edited(&[set_text("p1", "")]);
    assert!(
        xml.contains(r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr></w:p>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), [""]);
}

#[test]
fn sets_the_text_of_a_cell_in_one_paragraph_of_its_first_paragraph() {
    let quote = r#"<w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>a</w:t></w:r></w:p>"#;
    let first = format!(
        r#"<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>{quote}{}</w:tc>"#,
        p("b")
    );
    let body = table(2, &[format!("<w:tr>{first}{}</w:tr>", cell("", "c"))]);
    let file = File::new(&body);
    let (xml, blocks) = file.edited(&[set_text("t1/r1/c1", "45")]);
    assert!(
        xml.contains(r#"<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr><w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:rPr><w:i/></w:rPr><w:t>45</w:t></w:r></w:p></w:tc>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["45", "c", "end"]);
    assert_eq!(style_at(&blocks, "t1/r1/c1/p1"), Some("Quote"));
    let (_, blocks) = file.edited(&[set_text("t1/r1/c2", "d")]);
    assert_eq!(texts(&blocks), ["a", "b", "d", "end"]);
}

#[test]
fn refuses_a_set_text_of_a_table_of_a_cell_it_lacks_or_of_one_end_of_a_range() {
    let body = format!(
        r#"{}<w:p><w:bookmarkStart w:id="1" w:name="b"/><w:r><w:t>x</w:t></w:r></w:p><w:p><w:bookmarkEnd w:id="1"/></w:p>"#,
        table(1, &[format!("<w:tr>{}</w:tr>", cell("", "a"))])
    );
    let file = File::new(&body);
    assert_eq!(
        file.fault(&[set_text("t1", "x")]),
        (
            Some(0),
            NamedFault::WrongKind {
                at: at("t1"),
                needs: "a paragraph or a cell"
            }
        )
    );
    assert_eq!(
        file.fault(&[set_text("t1/r1/c2", "x")]),
        (Some(0), NamedFault::NoBlock(at("t1/r1/c2")))
    );
    assert_eq!(
        file.fault(&[set_text("p2", "y")]),
        (
            Some(0),
            NamedFault::RangeEnd {
                element: "w:bookmarkStart"
            }
        )
    );
}

#[test]
fn inserts_a_row_with_the_properties_of_the_row_and_of_its_cells() {
    let first = r#"<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:cnfStyle w:val="100000000000"/><w:shd w:val="clear" w:fill="FF0000"/></w:tcPr><w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>a</w:t></w:r></w:p></w:tc>"#;
    let anchor = format!(
        r#"<w:tr><w:trPr><w:cantSplit/><w:cnfStyle w:val="100000000000"/></w:trPr>{first}{}</w:tr>"#,
        cell("", "b")
    );
    let file = File::new(&table(2, &[anchor]));
    let (xml, blocks) = file.edited(&[row("t1/r1", Place::After, &["x\ty"])]);
    assert!(
        xml.contains(r#"</w:tr><w:tr><w:trPr><w:cantSplit/></w:trPr><w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:shd w:val="clear" w:fill="FF0000"/></w:tcPr><w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>x</w:t><w:tab/><w:t>y</w:t></w:r></w:p></w:tc><w:tc><w:p></w:p></w:tc></w:tr></w:tbl>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["a", "b", "x\ty", "", "end"]);
    assert_eq!(style_at(&blocks, "t1/r2/c1/p1"), Some("Quote"));
    let (_, blocks) = file.edited(&[
        row("t1/r1", Place::Before, &[]),
        row("t1/r1", Place::After, &["after"]),
    ]);
    assert_eq!(texts(&blocks), ["", "", "a", "b", "after", "", "end"]);
    assert_eq!(
        file.fault(&[row("t1/r1", Place::After, &["1", "2", "3"])]),
        (Some(0), NamedFault::TooManyCells { given: 3, cells: 2 })
    );
}

/// A table of three rows whose first column merges the first two rows, and the number of
/// `w:vMerge` elements of the new row of `edit` on it.
fn merges_of_new_row(edit: &NamedEdit) -> usize {
    let rows = [
        format!(
            "<w:tr>{}{}</w:tr>",
            cell(r#"<w:vMerge w:val="restart"/>"#, "top"),
            cell("", "1")
        ),
        format!("<w:tr>{}{}</w:tr>", cell("<w:vMerge/>", ""), cell("", "2")),
        format!("<w:tr>{}{}</w:tr>", cell("", "3"), cell("", "4")),
    ];
    let file = File::new(&table(2, &rows));
    let (xml, _) = file.edited(std::slice::from_ref(edit));
    xml.matches("<w:vMerge").count() - 2
}

#[test]
fn a_new_cell_continues_a_vertical_merge_that_goes_on_past_it() {
    assert_eq!(merges_of_new_row(&row("t1/r1", Place::After, &[])), 1);
    assert_eq!(merges_of_new_row(&row("t1/r2", Place::Before, &[])), 1);
    assert_eq!(merges_of_new_row(&row("t1/r1", Place::Before, &[])), 0);
    assert_eq!(merges_of_new_row(&row("t1/r2", Place::After, &[])), 0);
    assert_eq!(merges_of_new_row(&row("t1/r3", Place::Before, &[])), 0);
}

#[test]
fn refuses_a_text_for_a_cell_that_continues_a_merge_and_cells_in_a_content_control() {
    let rows = [
        format!(
            "<w:tr>{}</w:tr>",
            cell(r#"<w:vMerge w:val="restart"/>"#, "top")
        ),
        format!("<w:tr>{}</w:tr>", cell("<w:vMerge/>", "")),
        format!(
            "<w:tr><w:sdt><w:sdtContent>{}</w:sdtContent></w:sdt></w:tr>",
            cell("", "c")
        ),
    ];
    let file = File::new(&table(1, &rows));
    assert_eq!(
        file.fault(&[row("t1/r1", Place::After, &["x"])]),
        (Some(0), NamedFault::MergedCellText { cell: 1 })
    );
    assert_eq!(
        file.fault(&[row("t1/r3", Place::After, &[])]),
        (Some(0), NamedFault::WrappedCells)
    );
    assert_eq!(
        file.fault(&[row("t1", Place::After, &[])]),
        (
            Some(0),
            NamedFault::WrongKind {
                at: at("t1"),
                needs: "a row"
            }
        )
    );
}

#[test]
fn a_row_with_a_grid_before_merges_by_the_grid_column_of_its_cells() {
    let rows = [
        format!(
            r#"<w:tr><w:trPr><w:gridBefore w:val="1"/><w:gridAfter w:val="1"/></w:trPr>{}</w:tr>"#,
            cell(r#"<w:vMerge w:val="restart"/>"#, "top")
        ),
        format!(
            "<w:tr>{}{}{}</w:tr>",
            cell("", "a"),
            cell("<w:vMerge/>", ""),
            cell("", "b")
        ),
    ];
    let file = File::new(&table(3, &rows));
    let (xml, blocks) = file.edited(&[row("t1/r1", Place::After, &[])]);
    assert!(
        xml.contains(r#"<w:tr><w:trPr><w:gridBefore w:val="1"/><w:gridAfter w:val="1"/></w:trPr><w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p></w:p></w:tc></w:tr>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["top", "", "a", "", "b", "end"]);
}

#[test]
fn comments_on_a_paragraph_and_adds_the_comments_part() {
    let body = r#"<w:p><w:pPr><w:jc w:val="left"/></w:pPr><w:r><w:t>Pay now</w:t></w:r></w:p>"#;
    let file = File::new(body);
    let (bytes, blocks) = file.edited_file(&[comment("p1", None)]);
    let main = part_text(&bytes, "word/document.xml");
    assert!(
        main.contains(r#"<w:pPr><w:jc w:val="left"/></w:pPr><w:commentRangeStart w:id="0"/><w:r><w:t>Pay now</w:t></w:r><w:commentRangeEnd w:id="0"/><w:r><w:commentReference w:id="0"/></w:r></w:p>"#),
        "{main}"
    );
    let comments = part_text(&bytes, "word/comments.xml");
    assert!(
        comments.contains(r#"<w:comment w:id="0" w:author="Ann"><w:p><w:r><w:annotationRef/></w:r><w:r><w:t>Check this.</w:t></w:r></w:p></w:comment>"#),
        "{comments}"
    );
    let relationships = part_text(&bytes, "word/_rels/document.xml.rels");
    assert!(
        relationships.contains(r#"<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/>"#),
        "{relationships}"
    );
    let types = part_text(&bytes, "[Content_Types].xml");
    assert!(
        types.contains(r#"<Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/></Types>"#),
        "{types}"
    );
    assert_eq!(texts(&blocks), ["Pay now"]);
}

#[test]
fn comments_on_the_one_match_of_a_find_and_cuts_its_run() {
    let file = File::new(&p("Pay in 30 days now"));
    let (xml, blocks) = file.edited(&[comment("p1", Some("30 days"))]);
    assert!(
        xml.contains(r#"<w:r><w:t xml:space="preserve">Pay in </w:t></w:r><w:commentRangeStart w:id="0"/><w:r><w:t>30 days</w:t></w:r><w:commentRangeEnd w:id="0"/><w:r><w:commentReference w:id="0"/></w:r><w:r><w:t xml:space="preserve"> now</w:t></w:r>"#),
        "{xml}"
    );
    assert_eq!(texts(&blocks), ["Pay in 30 days now"]);
    let runs =
        "<w:p><w:r><w:t>Pay </w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>now</w:t></w:r></w:p>";
    let (xml, _) = File::new(runs).edited(&[comment("p1", Some("now"))]);
    assert!(
        xml.contains(r#"<w:commentRangeStart w:id="0"/><w:r><w:rPr><w:b/></w:rPr><w:t>now</w:t></w:r><w:commentRangeEnd w:id="0"/>"#),
        "{xml}"
    );
    assert_eq!(
        File::new(&p("one")).fault(&[comment("p1", Some("two"))]),
        (Some(0), NamedFault::TextNotFound)
    );
}

#[test]
fn adds_a_comment_to_the_comments_part_with_the_next_id() {
    let body = format!(
        r#"<w:p><w:commentRangeStart w:id="7"/><w:r><w:t>x</w:t></w:r><w:commentRangeEnd w:id="7"/></w:p>{}"#,
        p("y")
    );
    let held = r#"<w:comment w:id="3" w:author="Bo"><w:p/></w:comment>"#;
    let file = File::with(&body, |builder| {
        builder
            .relationship("word/document.xml", "c", "comments", "comments.xml")
            .part("word/comments.xml", crate::testing::word("comments", held))
    });
    let (bytes, _) = file.edited_file(&[comment("p2", None), comment("p1", None)]);
    let comments = part_text(&bytes, "word/comments.xml");
    assert!(
        comments.contains(r#"<w:comment w:id="8" w:author="Ann">"#)
            && comments.contains(r#"<w:comment w:id="9" w:author="Ann">"#)
            && comments.ends_with("</w:comment></w:comments>"),
        "{comments}"
    );
    let types = part_text(&bytes, "[Content_Types].xml");
    assert!(!types.contains("comments"), "{types}");
}

#[test]
fn puts_a_new_style_before_the_start_of_a_comment_in_either_order() {
    let file = File::new(&p("text"));
    for edits in [
        [comment("p1", None), super::style("p1", "Quote")],
        [super::style("p1", "Quote"), comment("p1", None)],
    ] {
        let (xml, blocks) = file.edited(&edits);
        assert!(
            xml.contains(
                r#"<w:p><w:pPr><w:pStyle w:val="Quote"/></w:pPr><w:commentRangeStart w:id="0"/>"#
            ),
            "{xml}"
        );
        assert_eq!(style_at(&blocks, "p1"), Some("Quote"));
    }
}

#[test]
fn refuses_a_comment_without_an_author_or_on_a_table() {
    let file = File::new(&table(1, &[format!("<w:tr>{}</w:tr>", cell("", "a"))]));
    let anonymous = NamedEdit::Comment {
        at: at("p1"),
        text: "x".to_owned(),
        find: None,
        author: " ".to_owned(),
    };
    assert_eq!(file.fault(&[anonymous]), (Some(0), NamedFault::EmptyAuthor));
    assert_eq!(
        file.fault(&[comment("t1", None)]),
        (
            Some(0),
            NamedFault::WrongKind {
                at: at("t1"),
                needs: "a paragraph"
            }
        )
    );
}

/// The file of two paragraphs with an image after each, the second one inch wide.
fn two_images() -> (Vec<u8>, Vec<crate::TextBlock>) {
    let file = File::new(&format!("{}{}", p("one"), p("two")));
    file.edited_file(&[
        image("p1", (2, 1), (None, None)),
        image("p2", (2, 1), (Some(inches(1)), None)),
    ])
}

#[test]
fn inserts_images_with_their_sizes_ids_and_relationships() {
    let (bytes, blocks) = two_images();
    let main = part_text(&bytes, "word/document.xml");
    assert!(
        main.contains(r#"<wp:extent cx="1828800" cy="914400"/><wp:docPr id="1" name="Picture 1" descr="A chart"/>"#),
        "{main}"
    );
    assert!(
        main.contains(r#"<wp:extent cx="914400" cy="457200"/><wp:docPr id="2" name="Picture 2" descr="A chart"/>"#),
        "{main}"
    );
    assert!(main.contains(r#"<a:blip r:embed="rId2"/>"#), "{main}");
    assert!(main.contains(r#"<a:blip r:embed="rId3"/>"#), "{main}");
    assert_eq!(texts(&blocks), ["one", "{PICTURE}", "two", "{PICTURE}"]);
}

#[test]
fn inserts_images_with_their_parts_and_one_content_type() {
    let (bytes, _) = two_images();
    let relationships = part_text(&bytes, "word/_rels/document.xml.rels");
    assert!(
        relationships.contains(r#"<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image2.png"/>"#),
        "{relationships}"
    );
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    assert!(package.part("word/media/image1.png").is_some());
    let types = part_text(&bytes, "[Content_Types].xml");
    assert_eq!(types.matches(r#"Extension="png""#).count(), 1, "{types}");
}

#[test]
fn makes_an_image_wider_than_its_column_as_wide_as_the_column() {
    let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/></w:sectPr>"#;
    let file = File::new(&format!("{}{section}", p("one")));
    let (xml, _) = file.edited(&[image("p1", (10, 5), (None, None))]);
    assert!(
        xml.contains(r#"<wp:extent cx="5943600" cy="2971800"/>"#),
        "{xml}"
    );
    let (xml, _) = file.edited(&[image("p1", (10, 5), (None, Some(inches(4))))]);
    assert!(
        xml.contains(r#"<wp:extent cx="7315200" cy="3657600"/>"#),
        "{xml}"
    );
}

#[test]
fn refuses_an_image_without_a_text_that_describes_it_or_at_a_row() {
    let file = File::new(&table(1, &[format!("<w:tr>{}</w:tr>", cell("", "a"))]));
    let mut nameless = image("p1", (1, 1), (None, None));
    if let NamedEdit::InsertImage { alt, .. } = &mut nameless {
        alt.clear();
    }
    assert_eq!(file.fault(&[nameless]), (Some(0), NamedFault::EmptyAlt));
    assert_eq!(
        file.fault(&[image("t1/r1", (1, 1), (None, None))]),
        (
            Some(0),
            NamedFault::WrongKind {
                at: at("t1/r1"),
                needs: "a paragraph or a table"
            }
        )
    );
    assert_eq!(
        file.fault(&[image("p1", (1, 1), (Some(Length::ZERO), None))]),
        (Some(0), NamedFault::ImageSize)
    );
    assert!(
        ImageFile::new(ImageFormat::Gif, Vec::new(), (inches(1), inches(1))).is_none()
            && ImageFile::new(ImageFormat::Png, Vec::new(), (Length::ZERO, inches(1))).is_none()
    );
}