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
use f_office_units::Length;

use super::run_of;
use crate::grid::{DOT, TextObject};
use crate::layout::testing::{NORMAL, find, lay_out, on_base_with, p, pass_with, table};
use crate::ns::{A, PIC, R, WP};
use crate::numbering::Numbering;
use crate::quirks::{TurnedAcrossDots, TurnedLineRoom, TurnedPicture};

/// A table of one row: a plain cell with "a", and a cell with the text direction `direction`
/// holding "bc", then a paragraph "z".
fn turned(direction: &str) -> String {
    let cell = format!(
        r#"<w:tcPr><w:textDirection w:val="{direction}"/></w:tcPr>{}"#,
        p("bc")
    );
    table("", &[2000, 600], &[("", &[&p("a"), &cell])]) + &p("z")
}

#[test]
fn turns_the_text_of_a_cell_that_reads_up() {
    let list = lay_out(&turned("btLr"), NORMAL, None);
    assert!(
        run_of(&list, 'b')
            .turn
            .is_some_and(|turn| turn.yx < 0 && turn.xy > 0)
    );
    let ((_, bx, by), (_, cx, cy)) = (find(&list, 'b'), find(&list, 'c'));
    assert_eq!(bx, cx);
    assert!(cy < by);
    // The turned text adds nothing to the row's height.
    let plain = table("", &[2000, 600], &[("", &[&p("a"), &p("")])]) + &p("z");
    assert_eq!(
        find(&list, 'z').2,
        find(&lay_out(&plain, NORMAL, None), 'z').2
    );
}

#[test]
fn turns_the_text_of_a_cell_that_reads_down() {
    let list = lay_out(&turned("tbRl"), NORMAL, None);
    assert!(
        run_of(&list, 'b')
            .turn
            .is_some_and(|turn| turn.yx > 0 && turn.xy < 0)
    );
    let ((_, bx, by), (_, cx, cy)) = (find(&list, 'b'), find(&list, 'c'));
    assert_eq!(bx, cx);
    assert!(cy > by);
    // The first line's top side lies at the cell's text end, so its baseline lies left of it.
    let (_, ax, _) = find(&list, 'a');
    assert!(bx > ax);
}

/// A table of three rows of exactly 400 twips: a plain cell in each, "a", "b" and "c", and
/// beside them a cell with the text direction `direction` that starts a vertical merge over
/// the three rows and holds `text`, then a paragraph "z".
fn turned_region(direction: &str, text: &str) -> String {
    let start = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/><w:textDirection w:val="{direction}"/></w:tcPr>{}"#,
        p(text)
    );
    let on = "<w:tcPr><w:vMerge/></w:tcPr><w:p/>";
    let exact = r#"<w:trHeight w:val="400" w:hRule="exact"/>"#;
    let rows: &[(&str, &[&str])] = &[
        (exact, &[&p("a"), &start]),
        (exact, &[&p("b"), on]),
        (exact, &[&p("c"), on]),
    ];
    table("", &[2000, 600], rows) + &p("z")
}

#[test]
fn turns_the_text_of_a_merged_cell_over_the_whole_region() {
    let pass = |body: &str| lay_out(body, NORMAL, None);
    // The text is longer than one row of 20 pt is high and shorter than the region of 60 pt.
    let list = pass(&turned_region("btLr", "ghijkl"));
    assert!(
        run_of(&list, 'g')
            .turn
            .is_some_and(|turn| turn.yx < 0 && turn.xy > 0)
    );
    // One line along the region, which starts at its bottom, below the last row's text, and
    // reads up.
    let ((_, gx, gy), (_, lx, ly)) = (find(&list, 'g'), find(&list, 'l'));
    assert_eq!(gx, lx);
    assert!(ly < gy);
    assert!(gy > find(&list, 'c').2);
    // The rows keep the heights of their plain cells.
    let plain = table(
        "",
        &[2000, 600],
        &[
            (
                r#"<w:trHeight w:val="400" w:hRule="exact"/>"#,
                &[&p("a"), &p("")],
            ),
            (
                r#"<w:trHeight w:val="400" w:hRule="exact"/>"#,
                &[&p("b"), &p("")],
            ),
            (
                r#"<w:trHeight w:val="400" w:hRule="exact"/>"#,
                &[&p("c"), &p("")],
            ),
        ],
    ) + &p("z");
    assert_eq!(find(&list, 'z').2, find(&pass(&plain), 'z').2);
    // Text that reads down starts at the region's top and stays in it.
    let down = pass(&turned_region("tbRl", "ghijkl"));
    let ((_, gx, gy), (_, lx, ly)) = (find(&down, 'g'), find(&down, 'l'));
    assert_eq!(gx, lx);
    assert!(gy < find(&down, 'b').2 && ly > gy);
}

/// A table of one row: a plain cell with "a", and a cell of the text direction `direction`
/// that holds the lines "b" and "c" of 32 pt in one paragraph, with the line spacing
/// attributes `spacing`.
fn turned_lines(direction: &str, spacing: &str) -> String {
    let run = |t: &str| {
        format!(r#"<w:r><w:rPr><w:sz w:val="64"/><w:szCs w:val="64"/></w:rPr><w:t>{t}</w:t></w:r>"#)
    };
    let cell = format!(
        r#"<w:tcPr><w:textDirection w:val="{direction}"/></w:tcPr><w:p><w:pPr><w:spacing w:before="0" w:after="0" {spacing}/></w:pPr>{}<w:r><w:br/></w:r>{}</w:p>"#,
        run("b"),
        run("c")
    );
    table("", &[2000, 2000], &[("", &[&p("a"), &cell])])
}

#[test]
fn makes_each_turned_line_a_32nd_of_its_size_taller_where_the_target_does() {
    let point = Length::UNITS_PER_POINT;
    for direction in ["btLr", "tbRl"] {
        // Where the first and the second line lie across the cell, in the direction in which
        // the lines stack.
        let places = |spacing: &str, room: TurnedLineRoom| {
            let target = on_base_with(|p| p.with_variant(room));
            let body = turned_lines(direction, spacing);
            let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
            let sign = if direction == "btLr" { 1 } else { -1 };
            (find(&list, 'b').1 * sign, find(&list, 'c').1 * sign)
        };
        // The spacing, how much further apart the two lines lie, and how much further the
        // first line lies: a 32nd of 32 pt on each line, half of it above the text.
        for (spacing, apart, first) in [
            ("", point, point / 2),
            (r#"w:line="480" w:lineRule="auto""#, 2 * point, point / 2),
            (r#"w:line="650" w:lineRule="atLeast""#, point / 2, 0),
            (r#"w:line="670" w:lineRule="atLeast""#, 0, -point / 2),
            (r#"w:line="800" w:lineRule="exact""#, 0, 0),
        ] {
            let (b, c) = places(spacing, TurnedLineRoom::Upright);
            let (taller_b, taller_c) = places(spacing, TurnedLineRoom::SizeShare);
            let grown = (taller_c - taller_b) - (c - b);
            assert!(
                (grown - apart).abs() <= DOT,
                "{direction} {spacing}: {grown}"
            );
            let moved = taller_b - b;
            assert!(
                (moved - first).abs() <= DOT,
                "{direction} {spacing}: {moved}"
            );
        }
    }
}

/// A table of five rows of exactly 361 twips, whose tops lie at five fractions of a dot: in
/// each, a plain cell with "a" and a cell of the text direction `direction`, aligned as `align`
/// says, that holds one of "b" to "f".
fn turned_rows(direction: &str, align: &str) -> String {
    let plain = p("a");
    let turned: Vec<String> = ["b", "c", "d", "e", "f"]
        .iter()
        .map(|letter| {
            format!(
                r#"<w:tcPr><w:textDirection w:val="{direction}"/><w:vAlign w:val="{align}"/></w:tcPr>{}"#,
                p(letter)
            )
        })
        .collect();
    let cells: Vec<[&str; 2]> = turned.iter().map(|cell| [plain.as_str(), cell]).collect();
    let height = r#"<w:trHeight w:val="361" w:hRule="exact"/>"#;
    let rows: Vec<(&str, &[&str])> = cells.iter().map(|pair| (height, &pair[..])).collect();
    table("", &[2000, 600], &rows)
}

/// Where the turned line of each of the five rows of [`turned_rows`] lies across the page,
/// where the target's `TurnedAcrossDots` is `dots`.
fn turned_row_places(direction: &str, align: &str, dots: TurnedAcrossDots) -> [i64; 5] {
    let target = on_base_with(|p| p.with_variant(dots));
    let body = turned_rows(direction, align);
    let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
    ['b', 'c', 'd', 'e', 'f'].map(|letter| find(&list, letter).1)
}

#[test]
fn puts_a_turned_line_on_one_whole_dot_across_in_every_row_where_the_target_does() {
    let page = turned_row_places("btLr", "top", TurnedAcrossDots::PageDots);
    assert!(
        page.iter().all(|&x| x == page[0] && x.rem_euclid(DOT) == 0),
        "{page:?}"
    );
    // Laid out from each row's top, the line moves with the fraction of a dot at which its row
    // starts.
    let frame = turned_row_places("btLr", "top", TurnedAcrossDots::FrameDots);
    assert!(frame.iter().any(|&x| x != frame[0]), "{frame:?}");
}

#[test]
fn keeps_the_places_from_the_row_top_for_other_turned_cells_where_the_target_does() {
    // Text that reads down, and text that reads up in a centred or bottom-aligned cell, lies
    // where it lies without the rule.
    for (direction, align) in [("tbRl", "top"), ("btLr", "center"), ("btLr", "bottom")] {
        let page = turned_row_places(direction, align, TurnedAcrossDots::PageDots);
        let frame = turned_row_places(direction, align, TurnedAcrossDots::FrameDots);
        assert_eq!(page, frame, "{direction} {align}");
        assert!(
            frame.iter().any(|&x| x != frame[0]),
            "{direction} {align}: {frame:?}"
        );
    }
}

#[test]
fn writes_a_turned_line_on_the_page_dots_where_the_writer_writes_a_text_objects_start() {
    // On a target that puts the lines on the page's dots, each turned line lies where the
    // target's writer writes a text object's start at a whole dot of the page; a writer with
    // an offset across the page moves some of them off their dots.
    let mut moved = false;
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let quirks = profile.quirks();
        if quirks.turned_across_dots != TurnedAcrossDots::PageDots {
            continue;
        }
        let (device, dot) = (profile.device(), profile.device_dot().units());
        let body = turned_rows("btLr", "top");
        let list = pass_with(
            &body,
            ("", None),
            None,
            Numbering::default(),
            (device, quirks),
        )
        .list;
        let page = &list.pages()[0];
        let object =
            TextObject::of(&device.with_page(page.width(), page.height(), page.orientation()));
        for letter in ['b', 'c', 'd', 'e', 'f'] {
            let x = find(&list, letter).1;
            let on_dot = Length::from_units(f_office_units::div_round(x, dot) * dot);
            assert_eq!(
                x,
                object.written_start_of(on_dot).units(),
                "{target} {letter}"
            );
            moved |= x != on_dot.units();
        }
    }
    assert!(moved);
}

#[test]
fn takes_the_text_edge_of_a_cell_after_a_turned_cell_from_the_page_columns_edge() {
    // A left margin of 1,238 twips and, in mode 14, a table at the indent 0 with cell margins
    // of 108 twips: the third column's text starts 2,850 twips from the page's left edge,
    // exactly half a dot past a whole dot where a dot is 3,048 half-EMUs, so its dot depends
    // on the edge of the page's column being a length of its own in the sum of the text edge.
    // An upright cell after a turned cell takes the dot of the same cell without one.
    let page = r#"<w:sectPr><w:pgMar w:left="1238" w:right="1138"/></w:sectPr>"#;
    let body = |second: &str| {
        let rows: &[(&str, &[&str])] = &[
            ("", &[&p("a"), second, &p("d")]),
            ("", &[&p("e"), &p("f"), &p("g")]),
        ];
        table(
            r#"<w:tblInd w:w="0" w:type="dxa"/>"#,
            &[556, 1056, 2207],
            rows,
        ) + page
    };
    let turned = format!(
        r#"<w:tcPr><w:textDirection w:val="btLr"/></w:tcPr>{}"#,
        p("bc")
    );
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let on = (profile.device(), profile.quirks());
        let x = |second: &str| {
            let pass = pass_with(
                &body(second),
                (NORMAL, Some(14)),
                None,
                Numbering::default(),
                on,
            );
            find(&pass.list, 'g').1
        };
        assert_eq!(x(&turned), x(&p("bc")), "{target}");
    }
}

#[test]
fn takes_a_turned_lines_dot_at_a_tie_as_the_sum_of_its_sides_parts_gives_it() {
    // Two tables at the indent 0 whose second column's text starts 1,794 twips from the page's
    // left edge, exactly half a dot past a whole dot: with a left margin of 1,238 twips and
    // cell margins of 108, the three parts of the edge sum to the lower dot in fixed point;
    // with 1,242 and 106, to the higher. On a target whose turned lines lie on the page's dots,
    // a turned line of 12 pt of the test font, whose height rounds down and whose place ties
    // there, moves with the upright text of its column, in mode 14, where the table's edge lies
    // at the indent, and in mode 15, where its text does. A line of 11 pt, whose height rounds
    // up, takes its place from its bottom, which does not tie, and stays.
    let body = |(page, margin, first): (i64, i64, i64), size: u32| {
        let props = format!(
            r#"<w:tblInd w:w="0" w:type="dxa"/><w:tblCellMar><w:left w:w="{margin}" w:type="dxa"/></w:tblCellMar>"#
        );
        let turned = format!(
            r#"<w:tcPr><w:textDirection w:val="btLr"/></w:tcPr><w:p><w:pPr><w:rPr><w:sz w:val="{size}"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="{size}"/></w:rPr><w:t>t</w:t></w:r></w:p>"#
        );
        let height = r#"<w:trHeight w:val="600" w:hRule="exact"/>"#;
        let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &p("u")]), (height, &[&p("b"), &turned])];
        let section = format!(r#"<w:sectPr><w:pgMar w:left="{page}" w:right="1138"/></w:sectPr>"#);
        table(&props, &[first, 1200], rows) + &section
    };
    let mut checked = false;
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let on = (profile.device(), profile.quirks());
        if on.1.turned_across_dots != TurnedAcrossDots::PageDots {
            continue;
        }
        for (mode, firsts) in [(14, (556, 552)), (15, (448, 446))] {
            let places = |case, size| {
                let list = pass_with(
                    &body(case, size),
                    (NORMAL, Some(mode)),
                    None,
                    Numbering::default(),
                    on,
                )
                .list;
                (find(&list, 'u').1, find(&list, 't').1)
            };
            let down = (1238, 108, firsts.0);
            let up = (1242, 106, firsts.1);
            let (tie_down, tie_up) = (places(down, 24), places(up, 24));
            assert_ne!(tie_down.0, tie_up.0, "{target} {mode}");
            assert_eq!(
                tie_down.1 - tie_up.1,
                tie_down.0 - tie_up.0,
                "{target} {mode}"
            );
            let (off_down, off_up) = (places(down, 22), places(up, 22));
            assert_eq!(off_down.1, off_up.1, "{target} {mode}");
            checked = true;
        }
    }
    assert!(checked);
}

/// A table of one row of an exact height of 200 pt: a plain cell with "x", and a cell of text
/// that reads up with "a", an inline picture of 36 by 18 pt and "b".
fn turned_picture() -> String {
    let picture = format!(
        r#"<w:r><w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="457200" cy="228600"/><a:graphic xmlns:a="{A}"><a:graphicData><pic:pic xmlns:pic="{PIC}"><pic:blipFill><a:blip xmlns:r="{R}" r:embed="rId1"/></pic:blipFill><pic:spPr/></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#
    );
    let cell = format!(
        r#"<w:tcPr><w:textDirection w:val="btLr"/></w:tcPr><w:p><w:r><w:t>a</w:t></w:r>{picture}<w:r><w:t>b</w:t></w:r></w:p>"#
    );
    table(
        "",
        &[2000, 2000],
        &[(
            r#"<w:trHeight w:val="4000" w:hRule="exact"/>"#,
            &[&p("x"), &cell],
        )],
    )
}

#[test]
fn gives_an_upright_picture_of_a_turned_cell_its_height_along_the_line() {
    let point = Length::UNITS_PER_POINT;
    // Where "b" lies across the cell, in units, and how far along the line it lies from "a",
    // in device dots.
    let places = |pictures: TurnedPicture| {
        let target = on_base_with(|p| p.with_variant(pictures));
        let list = pass_with(
            &turned_picture(),
            ("", None),
            None,
            Numbering::default(),
            target,
        )
        .list;
        let ((_, ax, ay), (_, bx, by)) = (find(&list, 'a'), find(&list, 'b'));
        assert_eq!(ax, bx);
        (bx, ay - by)
    };
    let (in_frame_across, in_frame_along) = places(TurnedPicture::InFrame);
    let (upright_across, upright_along) = places(TurnedPicture::Upright);
    // Upright, the picture takes 18 pt along the line instead of 36, and its line reaches
    // 36 pt above the baseline instead of 18.
    assert!(
        (in_frame_along - upright_along - 18 * point / DOT).abs() <= 1,
        "{in_frame_along} {upright_along}"
    );
    assert!(
        (upright_across - in_frame_across - 18 * point).abs() <= DOT,
        "{in_frame_across} {upright_across}"
    );
}