f-office 0.2.2

Renders Office Open XML documents the way Microsoft Office does.
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
//! Layout tests of text: glyphs, fonts, ligatures, small capitals, outlines and fills.

use f_office_paint::{DisplayList, Item};

use super::{
    CARLITO, CARLITO_FONTS, CARLITO_RUN, SECTION, baseline_of, carlito, carlito_line,
    compatibility_mode, docx, fills, lines, para, points, render,
};

#[test]
fn writes_a_non_breaking_hyphen_as_a_hyphen() {
    let body = |hyphen: &str| {
        format!(
            r"<w:p><w:r>{CARLITO_RUN}<w:t>49</w:t>{hyphen}<w:t>28</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
        )
    };
    let glyphs = |list: &DisplayList| -> Vec<(String, Vec<u32>)> {
        list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Glyphs(run) => {
                    Some((run.text.clone(), run.glyphs.iter().map(|g| g.id).collect()))
                }
                _ => None,
            })
            .collect()
    };
    let plain = glyphs(&render(&docx(&body("<w:t>-</w:t>"), &[], "")));
    let kept = glyphs(&render(&docx(&body("<w:noBreakHyphen/>"), &[], "")));
    assert_eq!(kept, plain);
    assert_eq!(kept[0].0, "49-28");
    // A U+2011 in the text keeps its own text and draws the same glyph.
    let literal = glyphs(&render(&docx(&body("<w:t>\u{2011}</w:t>"), &[], "")));
    assert_eq!(literal[0].0, "49\u{2011}28");
    assert_eq!(literal[0].1, kept[0].1);
}

#[test]
fn draws_a_list_of_fonts_with_its_first_font() {
    let body = |font: &str| {
        format!(
            r#"<w:p><w:r><w:rPr><w:rFonts w:ascii="{font}" w:hAnsi="{font}"/></w:rPr><w:t>Water</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
        )
    };
    let plain = render(&docx(&body("Carlito"), &[], ""));
    let listed = render(&docx(&body("Carlito, Geneva, sans-serif"), &[], ""));
    assert_eq!(lines(&listed), lines(&plain));
    assert_eq!(lines(&listed)[0].len(), 1);
}

#[test]
fn warns_of_a_font_that_a_stand_in_draws() {
    // The paragraph mark takes the font of the text.
    let body = |font: &str| {
        let fonts = format!(r#"<w:rPr><w:rFonts w:ascii="{font}" w:hAnsi="{font}"/></w:rPr>"#);
        format!(
            r"<w:p><w:pPr>{fonts}</w:pPr><w:r>{fonts}<w:t>Water</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
        )
    };
    let fonts = carlito();
    let warnings = |font: &str| -> Vec<String> {
        let laid_out =
            super::Document::open(&docx(&body(font), &[], ""), &fonts, &super::Options::base())
                .unwrap();
        let warnings = laid_out.warnings.iter();
        warnings.map(|(warning, _)| warning.to_string()).collect()
    };
    assert_eq!(warnings("Carlito"), Vec::<String>::new());
    assert_eq!(warnings("Calibri"), ["font Calibri is drawn with Carlito"]);
}

#[test]
fn a_font_file_that_does_not_load_draws_no_glyph_and_warns_and_an_unchosen_file_is_not_read() {
    // Two copies of Carlito in a font folder, given in this order: the layout chooses the first
    // of the equal faces.
    let name = format!("f-office-font-files-{}", std::process::id());
    let folder = std::env::temp_dir().join(name);
    std::fs::create_dir_all(&folder).unwrap();
    let (first, second) = (folder.join("a-carlito.ttf"), folder.join("b-carlito.ttf"));
    std::fs::write(&first, CARLITO).unwrap();
    std::fs::write(&second, CARLITO).unwrap();
    let mut both = super::FontDb::new();
    both.add_files(&[first.clone(), second.clone()]).unwrap();
    assert_eq!(both.load(f_office_fonts::FontId::from_index(0)), Ok(()));
    let mut only_first = super::FontDb::new();
    std::fs::remove_file(&second).unwrap();
    only_first.add_files(std::slice::from_ref(&first)).unwrap();
    std::fs::remove_file(&first).unwrap();
    std::fs::remove_dir(&folder).unwrap();
    let docx = docx(
        &format!(
            r"<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Water</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
        ),
        &[],
        "",
    );
    let open = |fonts| super::Document::open(&docx, fonts, &super::Options::base()).unwrap();
    let fonts_of = |list: &DisplayList| -> Vec<u32> {
        let items = list.pages().iter().flat_map(f_office_paint::Page::items);
        let runs = items.filter_map(|item| match item {
            Item::Glyphs(run) => Some(run.font.index()),
            _ => None,
        });
        runs.collect()
    };
    // Neither file is there any more: the first one loaded before, and the layout never reads
    // the second one.
    let laid_out = open(&both);
    assert!(laid_out.warnings.is_empty());
    assert_eq!(fonts_of(laid_out.value.display_list()), [0]);
    // The face of the file that did not load counts as missing: no glyph is drawn with it, and
    // the warning names the file by its name in the folder.
    let laid_out = open(&only_first);
    assert_eq!(fonts_of(laid_out.value.display_list()), Vec::<u32>::new());
    let warnings: Vec<_> = laid_out
        .warnings
        .iter()
        .map(|(warning, _)| warning)
        .collect();
    let not_read = warnings
        .iter()
        .find(|warning| warning.kind() == "font-file-not-read")
        .unwrap();
    assert!(
        not_read
            .to_string()
            .starts_with("font file a-carlito.ttf did not load"),
        "{not_read}"
    );
}

#[test]
fn lowers_text_in_a_line_with_other_text_but_not_a_line_lowered_as_a_whole() {
    let run = |position: &str, text: &str| {
        format!(
            r#"<w:r><w:rPr>{CARLITO_FONTS}<w:position w:val="{position}"/></w:rPr><w:t>{text}</w:t></w:r>"#
        )
    };
    let body = format!(
        r"<w:p>{}{}</w:p><w:p>{}</w:p><w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        run("-4", "Low"),
        run("0", "Level"),
        run("-4", "All"),
        run("0", "Next"),
    );
    let list = render(&docx(&body, &[], ""));
    let (ascent, line) = carlito_line();
    // In a line with other text, the lowered run moves 2 pt down, and the line grows by 2 pt.
    let level = baseline_of(&list, "Level");
    assert!((level - (36.0 + ascent)).abs() <= 0.12, "{level}");
    assert!((baseline_of(&list, "Low") - (level + 2.0)).abs() <= 0.12);
    // A line lowered as a whole keeps its glyphs where they were. The baselines move to the
    // 0.24 pt grid, so they can lie a grid step from the sums.
    let all = baseline_of(&list, "All");
    assert!((all - (level + line + 2.0)).abs() <= 0.3, "{all} {level}");
    let next = baseline_of(&list, "Next");
    assert!((next - (all + line)).abs() <= 0.3, "{next} {all}");
}

#[test]
fn draws_small_capitals_smaller_except_the_capitals() {
    let body = format!(
        r#"<w:p><w:r><w:rPr>{CARLITO_FONTS}<w:smallCaps/><w:sz w:val="24"/></w:rPr><w:t>Ab c</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let list = render(&docx(&body, &[], ""));
    let runs: Vec<(String, f64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => Some((run.text.clone(), points(run.size.units()))),
            _ => None,
        })
        .collect();
    // The small size is 9.5 pt, which is drawn at 9.6 pt on the device grid.
    assert_eq!(
        runs,
        [("A".to_owned(), 12.0), ("B C".to_owned(), 9.6)],
        "{runs:?}"
    );
}

#[test]
fn a_phantom_that_is_not_shown_takes_its_room_and_draws_nothing() {
    // The equation 1, a phantom of 23, then 4, in normal text (m:nor) of Carlito, the test's
    // only font. Each case gives the drawn text and the x of the 4.
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let r =
        |text: &str| format!("<m:r><m:rPr><m:nor/></m:rPr>{CARLITO_RUN}<m:t>{text}</m:t></m:r>");
    let equation = |settings: &str| {
        let body = format!(
            r#"<w:p><m:oMath xmlns:m="{math}">{}<m:phant><m:phantPr>{settings}</m:phantPr><m:e>{}</m:e></m:phant>{}</m:oMath></w:p>"#,
            r("1"),
            r("23"),
            r("4")
        );
        let list = render(&docx(&body, &[], ""));
        let mut text = String::new();
        let mut four = None;
        for item in list.pages()[0].items() {
            let Item::Glyphs(run) = item else { continue };
            for g in &run.glyphs {
                let ch = run.glyph_text(g).unwrap();
                text.push_str(ch);
                if ch == "4" {
                    four = Some(g.x.units());
                }
            }
        }
        (text, four.unwrap())
    };
    let (shown, at) = equation("");
    assert_eq!(shown, "1234");
    // Not shown, the phantom keeps its width; with zero width it takes none. After the gap the
    // 4 starts at its exact place, without the drawn rounding of the run before it, so the
    // places agree to a hundredth of a point.
    let (text, hidden) = equation(r#"<m:show m:val="0"/>"#);
    assert_eq!(text, "14");
    assert!((hidden - at).abs() < 254, "{hidden} {at}");
    let (text, narrow) = equation(r#"<m:show m:val="0"/><m:zeroWid/>"#);
    assert_eq!(text, "14");
    assert!(narrow < at, "{narrow} {at}");
}

/// The lowest and the highest point of the outline of Carlito's glyph for `ch`, in ems.
fn carlito_ink(ch: char) -> (f64, f64) {
    let mut fonts = f_office_fonts::FontDb::new();
    let id = fonts.add_font(CARLITO.to_vec()).unwrap()[0];
    let em = f64::from(fonts.metrics(id).unwrap().units_per_em);
    let outline = fonts.outline(id, fonts.glyph_id(id, ch).unwrap()).unwrap();
    let heights: Vec<f32> = outline
        .iter()
        .flat_map(|command| match *command {
            f_office_fonts::PathCommand::MoveTo(p) | f_office_fonts::PathCommand::LineTo(p) => {
                vec![p.y]
            }
            f_office_fonts::PathCommand::QuadTo(c, p) => vec![c.y, p.y],
            f_office_fonts::PathCommand::CubicTo(c, d, p) => vec![c.y, d.y, p.y],
            f_office_fonts::PathCommand::Close => Vec::new(),
        })
        .collect();
    let low = heights.iter().copied().fold(f32::MAX, f32::min);
    let high = heights.iter().copied().fold(f32::MIN, f32::max);
    (f64::from(low) / em, f64::from(high) / em)
}

/// The distance in points from the baseline of a plain line of 10 pt Carlito to the baseline
/// of the line after it, which holds the fraction `num` over `den` in normal text of Carlito,
/// and from that line to the plain line after it.
fn fraction_line(num: &str, den: &str) -> (f64, f64) {
    let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
    let r =
        |text: &str| format!(r"<m:r><m:rPr><m:nor/></m:rPr>{CARLITO_RUN}<m:t>{text}</m:t></m:r>");
    let body = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t>Top</w:t></w:r></w:p><w:p><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r><m:oMath xmlns:m="{math}"><m:f><m:num>{}</m:num><m:den>{}</m:den></m:f></m:oMath></w:p><w:p><w:r>{CARLITO_RUN}<w:t>End</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#,
        r(num),
        r(den)
    );
    let list = render(&docx(&body, &[], ""));
    let line = baseline_of(&list, "A");
    (
        line - baseline_of(&list, "Top"),
        baseline_of(&list, "End") - line,
    )
}

#[test]
fn the_room_below_an_inline_fraction_follows_the_ink_of_its_denominator() {
    // At 10 pt, the parts of an inline fraction are at 7 pt, and the denominator drops
    // 1030/2048 of 10 pt. Each distance lies on the device grid.
    let part = 7.0;
    let (above, below) = fraction_line("x", "x");
    // A deeper denominator moves the line after it down by the depth of its ink.
    let deep = fraction_line("x", "g");
    let expected = (carlito_ink('x').0 - carlito_ink('g').0) * part;
    assert!((deep.1 - below - expected).abs() < 0.25, "{deep:?} {below}");
    assert!((deep.0 - above).abs() < 0.01, "{deep:?} {above}");
    // Below the ink of x, which stands on its baseline, the line reaches as far as the
    // denominator drops: not as far as the descent of its font.
    let (ascent, height) = super::carlito_line();
    let reach = 10.0 * 1030.0 / 2048.0 - carlito_ink('x').0 * part;
    assert!(
        (below - ascent - reach).abs() < 0.25,
        "{below} {ascent} {height} {reach}"
    );
}

/// The text and x position in display list units of each glyph of a one-run paragraph of
/// Carlito "office", with the run properties `extra`, in compatibility mode `mode`.
fn office_glyphs(extra: &str, mode: u32) -> Vec<(String, i64)> {
    let body =
        format!("<w:p><w:r><w:rPr>{CARLITO_FONTS}{extra}</w:rPr><w:t>office</w:t></w:r></w:p>");
    let list = render(&docx(&body, &[], &compatibility_mode(mode)));
    let Some(Item::Glyphs(run)) = list.pages()[0].items().first() else {
        panic!("no glyph run");
    };
    run.glyphs
        .iter()
        .map(|g| {
            let text = run.glyph_text(g).unwrap();
            (text.to_owned(), g.x.units())
        })
        .collect()
}

#[test]
fn joins_standard_ligatures_only_when_the_run_turns_them_on() {
    let texts = |glyphs: &[(String, i64)]| glyphs.iter().map(|g| g.0.clone()).collect::<Vec<_>>();
    let plain = office_glyphs("", 15);
    assert_eq!(texts(&plain), ["o", "f", "f", "i", "c", "e"]);
    let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
    let ligatures = format!(r#"<w14:ligatures xmlns:w14="{w14}" w14:val="standardContextual"/>"#);
    let joined = office_glyphs(&ligatures, 15);
    assert_eq!(texts(&joined), ["o", "ffi", "c", "e"]);
    // Before mode 14, Word ignores the setting.
    assert_eq!(texts(&office_glyphs(&ligatures, 12)), texts(&plain));
    // The "ffi" of Carlito is 1,654 of 2,048 units wide at the default 10 pt, narrower than
    // its three letters.
    let ffi = joined[2].1 - joined[1].1;
    assert!((ffi - 1654 * 254_000 / 2048).abs() <= 1, "{ffi}");
    assert!(joined[3].1 < plain[5].1);
}

/// The text of each glyph of a paragraph of runs in compatibility mode 15, in order.
fn glyph_texts(runs: &str) -> Vec<String> {
    let list = render(&docx(
        &format!("<w:p>{runs}</w:p>"),
        &[],
        &compatibility_mode(15),
    ));
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => Some(
                run.glyphs
                    .iter()
                    .map(|g| run.glyph_text(g).unwrap().to_owned())
                    .collect::<Vec<_>>(),
            ),
            _ => None,
        })
        .flatten()
        .collect()
}

#[test]
fn joins_ligatures_across_runs_with_the_same_properties() {
    let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
    let run = |text: &str, extra: &str| {
        format!(
            r#"<w:r><w:rPr>{CARLITO_FONTS}<w14:ligatures xmlns:w14="{w14}" w14:val="standard"/>{extra}</w:rPr><w:t>{text}</w:t></w:r>"#
        )
    };
    assert_eq!(
        glyph_texts(&(run("of", "") + &run("fice", ""))),
        ["o", "ffi", "c", "e"]
    );
    // A run in another color keeps its glyphs apart.
    let red = r#"<w:color w:val="FF0000"/>"#;
    assert_eq!(
        glyph_texts(&(run("of", "") + &run("fice", red))),
        ["o", "f", "fi", "c", "e"]
    );
}

#[test]
fn outlines_the_glyphs_of_a_run_with_a_text_outline_in_yellow_for_a_theme_color() {
    let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
    let outlined = format!(
        r#"<w:p><w:r><w:rPr>{CARLITO_FONTS}<w14:textOutline xmlns:w14="{w14}" w14:w="12700"><w14:solidFill><w14:schemeClr w14:val="accent2"/></w14:solidFill></w14:textOutline></w:rPr><w:t>Outlined</w:t></w:r></w:p>"#
    );
    let list = render(&docx(&(outlined + &para("Plain")), &[], ""));
    let runs: Vec<_> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => Some((
                run.text.clone(),
                run.outline.map(|line| (line.width.units(), line.color)),
            )),
            _ => None,
        })
        .collect();
    let yellow = f_office_paint::Rgb {
        r: 255,
        g: 255,
        b: 0,
    };
    assert_eq!(
        runs,
        vec![
            (
                "Outlined".to_owned(),
                Some((crate::Length::UNITS_PER_POINT, yellow))
            ),
            ("Plain".to_owned(), None)
        ]
    );
}

#[test]
fn fills_highlights_shaded_paragraphs_and_cells() {
    let run = |props: &str, text: &str| {
        format!("<w:r><w:rPr>{CARLITO_FONTS}{props}</w:rPr><w:t>{text}</w:t></w:r>")
    };
    let cell = |fill: &str, text: &str| {
        format!(
            r#"<w:tc><w:tcPr><w:shd w:val="clear" w:fill="{fill}"/></w:tcPr><w:p>{}</w:p></w:tc>"#,
            run("", text)
        )
    };
    let body = format!(
        r#"<w:p>{}</w:p><w:p><w:pPr><w:shd w:val="clear" w:fill="00FF00"/><w:ind w:left="720"/></w:pPr>{}</w:p><w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{}{}</w:tr></w:tbl><w:sectPr>{SECTION}</w:sectPr>"#,
        run(r#"<w:highlight w:val="yellow"/>"#, "Marked"),
        run("", "Shaded"),
        cell("0000FF", "Blue"),
        cell("FFFFFF", "White"),
    );
    let list = render(&docx(&body, &[], ""));
    let rects = fills(&list);
    let find = |color: [u8; 3]| rects.iter().find(|r| r.4 == color).copied();
    // The highlight covers the word from the left margin.
    let marked = find([255, 255, 0]).unwrap();
    assert!(
        (marked.0 - 36.0).abs() < 0.25 && marked.2 > 20.0,
        "{rects:?}"
    );
    // The paragraph's fill spans the column from its indent to the right margin, and past both
    // by the reach of its border lines, 1.5 pt rounded down to dots of 0.24 pt.
    let shaded = find([0, 255, 0]).unwrap();
    assert!(
        (shaded.0 - 70.56).abs() < 0.01 && (shaded.2 - 194.88).abs() < 0.01,
        "{rects:?}"
    );
    // Both cells are filled across their 100 pt, the white one too.
    let blue = find([0, 0, 255]).unwrap();
    assert!((blue.2 - 100.0).abs() < 0.25 && blue.3 > 10.0, "{rects:?}");
    let white = find([255, 255, 255]).unwrap();
    assert!(
        (white.0 - blue.0 - 100.0).abs() < 0.25 && (white.2 - 100.0).abs() < 0.25,
        "{rects:?}"
    );
    // Each fill lies under the text that it fills.
    let items = list.pages()[0].items();
    let index = |pick: &dyn Fn(&Item) -> bool| items.iter().position(pick).unwrap();
    let blue_fill = index(&|i| matches!(i, Item::Rect(r) if r.color.b == 255 && r.color.r == 0));
    let blue_text = index(&|i| matches!(i, Item::Glyphs(g) if g.text == "Blue"));
    assert!(blue_fill < blue_text);
}