f-office-docx 0.2.2

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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! The borders of paragraphs outside tables: boxed paragraphs, the reach of the lines, at-least
//! lines and double lines.

use std::fmt::Write as _;

use f_office_paint::{DisplayList, Item};

use crate::layout::testing::{
    NORMAL, SINGLE, at, base, du, find, lay_out, on_base_with, p, pass_with, rects,
};
use crate::numbering::Numbering;
use crate::quirks::{
    BetweenBorders, BorderWidthUnit, BottomBorderParts, NoneBorders, SectionEndBorders,
};

#[test]
fn draws_the_side_lines_of_a_boxed_paragraph() {
    let side = r#"w:val="single" w:sz="4""#;
    let list = lay_out(
        &format!(
            r#"<w:p><w:pPr><w:pBdr><w:top {side} w:space="1"/><w:left {side} w:space="4"/><w:bottom {side} w:space="1"/><w:right {side} w:space="4"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#
        ),
        NORMAL,
        None,
    );
    let mut rects = rects(&list, 0);
    rects.sort_unstable();
    // The text runs from 300 to 2250 device dots. The side lines lie the 6 units of the
    // reach and the 4 pt space, rounded down to 16 units, outside it, and the top and bottom
    // lines run between them. The 0.5 pt lines are 2 units wide.
    let (top, bottom) = (rects[1], rects[2]);
    assert_eq!((top.0, top.2, top.1), (278, 2272 - 278, 300));
    assert_eq!((bottom.0, bottom.2), (278, 2272 - 278));
    let (left, right) = (rects[0], rects[3]);
    assert_eq!((left.0, left.2, right.0, right.2), (276, 2, 2272, 2));
    // The side lines run from the top line's top to the bottom line's bottom.
    assert_eq!((left.1, left.1 + left.3), (top.1, bottom.1 + bottom.3));
    assert_eq!((right.1, right.3), (left.1, left.3));
}

#[test]
fn extends_paragraph_borders_by_the_same_physical_reach_on_each_device() {
    let body = r#"<w:p><w:pPr><w:ind w:left="7" w:right="13"/><w:pBdr><w:top w:val="single" w:sz="4"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    for (dpi, left, right) in [(300, 295, 2253), (288, 283, 2163), (600, 591, 4507)] {
        let device = crate::grid::Device::per_inch(dpi).unwrap();
        let target = (device, crate::grid::base_quirks());
        let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
        let line = list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                Item::Rect(r) => Some(r),
                _ => None,
            })
            .unwrap();
        assert_eq!(line.x.units(), left * device.dots(1).units(), "{dpi}");
        assert_eq!(
            line.x.units() + line.width.units(),
            right * device.dots(1).units(),
            "{dpi}"
        );
    }
}

#[test]
fn puts_the_top_border_of_an_at_least_line_on_its_single_line() {
    let bordered = |spacing: &str| {
        lay_out(
            &format!(
                r#"<w:p><w:pPr><w:pBdr><w:top {SINGLE} w:space="1"/></w:pBdr>{spacing}</w:pPr><w:r><w:t>a</w:t></w:r></w:p>{}"#,
                p("b")
            ),
            NORMAL,
            None,
        )
    };
    let single = bordered("");
    let least = bordered(r#"<w:spacing w:line="320" w:lineRule="atLeast"/>"#);
    let top = |list: &DisplayList| rects(list, 0)[0].1;
    // The single line of the fake font at 10 pt starts under the 0.5 pt line and its 1 pt
    // space, at the 72 pt margin. A minimum of 16 pt puts the 6 pt above the single line, and
    // the border stands on the single line: as far above the baseline as above a single line.
    assert_eq!(top(&single), 300);
    let (a, b) = (at(&least, 'a').1, at(&single, 'a').1);
    assert_eq!(a - top(&least), b - top(&single));
    // The lines stay where the minimum puts them: the line is 6 pt (25 device dots) lower,
    // and the next paragraph comes 6 pt later.
    assert_eq!(a - b, 25);
    assert_eq!(at(&least, 'b').1 - at(&single, 'b').1, 25);
}

#[test]
fn draws_a_double_border_as_two_lines_with_a_gap_of_the_same_width() {
    // Lines of 1 pt (8 eighths), 20 twips each: the border takes 60 twips above the text.
    let bordered = r#"<w:p><w:pPr><w:pBdr><w:top w:val="double" w:sz="8"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let list = lay_out(bordered, NORMAL, None);
    assert_eq!(find(&list, 'a').2, base(1440 + 60));
    let lines: Vec<(i64, i64)> = rects(&list, 0).iter().map(|r| (r.1, r.3)).collect();
    assert_eq!(lines, [(du(1440), du(20)), (du(1480), du(20))]);
}

#[test]
fn keeps_the_space_of_a_border_of_none_where_the_target_keeps_it() {
    let body = format!(
        r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="none" w:sz="0" w:space="10"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>{}<w:p><w:pPr><w:pBdr><w:bottom w:val="nil" w:space="10"/></w:pBdr></w:pPr><w:r><w:t>c</w:t></w:r></w:p>{}"#,
        p("b"),
        p("d")
    );
    let lay = |rule| {
        let target = crate::layout::testing::target_at(300, |p| p.with_variant(rule));
        let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        let lines = ['a', 'b', 'c', 'd'].map(|c| at(&list, c).1);
        (lines, rects(&list, 0).len())
    };
    let (dropped, dropped_rects) = lay(NoneBorders::Dropped);
    let (kept, kept_rects) = lay(NoneBorders::KeepSpace);
    // With the rule, the 10 pt of the border of none, 41.67 dots, stand below the first
    // paragraph, and every later line lies that much lower; the border of nil takes nothing.
    // Neither draws a line.
    let shift = kept
        .iter()
        .zip(dropped)
        .map(|(k, d)| k - d)
        .collect::<Vec<_>>();
    assert_eq!(shift[0], 0);
    assert!(
        shift[1..].iter().all(|s| (41..=42).contains(s)),
        "{shift:?}"
    );
    assert_eq!((dropped_rects, kept_rects), (0, 0));
}

/// A rectangle of a page in device dots: x, y, width and height, as `rects` gives it.
type Rect = (i64, i64, i64, i64);

/// The baselines of the paragraphs `a` to `d` of three paragraphs with a between line of 3 pt and
/// a space of 6 pt and a plain one after them, and the rectangles of the first page in order,
/// laid out on a device of 300 dots an inch under `rule`.
fn between_group(rule: BetweenBorders) -> ([i64; 4], Vec<Rect>) {
    let between =
        r#"<w:pPr><w:pBdr><w:between w:val="single" w:sz="24" w:space="6"/></w:pBdr></w:pPr>"#;
    let body = ['a', 'b', 'c']
        .map(|c| format!("<w:p>{between}<w:r><w:t>{c}</w:t></w:r></w:p>"))
        .concat()
        + &p("d");
    let target = crate::layout::testing::target_at(300, |p| p.with_variant(rule));
    let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    let mut drawn = rects(&list, 0);
    drawn.sort_unstable();
    (['a', 'b', 'c', 'd'].map(|c| at(&list, c).1), drawn)
}

#[test]
fn adds_the_room_of_the_line_between_the_paragraphs_of_a_group_where_the_target_draws_it() {
    let (dropped, dropped_rects) = between_group(BetweenBorders::Dropped);
    let (drawn, _) = between_group(BetweenBorders::Drawn);
    assert_eq!(dropped_rects, []);
    // Each line between two paragraphs takes its 3 pt and twice its 6 pt space, 15 pt or 62.5
    // dots, so that the second paragraph lies that much lower and the third twice as much;
    // the paragraph after the group follows the third.
    let shift = drawn
        .iter()
        .zip(dropped)
        .map(|(d, p)| d - p)
        .collect::<Vec<_>>();
    assert_eq!(shift[0], 0);
    assert!((62..=63).contains(&shift[1]), "{shift:?}");
    assert!((124..=126).contains(&shift[2]), "{shift:?}");
    assert_eq!(shift[3], shift[2], "{shift:?}");
}

#[test]
fn draws_the_line_between_each_two_paragraphs_of_a_group_where_the_target_does() {
    let ([a, b, c, _], drawn) = between_group(BetweenBorders::Drawn);
    // Two lines of 3 pt, 12.5 dots drawn as 12, each between two paragraphs: none above the
    // first or below the last.
    let tops = drawn
        .iter()
        .map(|&(_, top, _, height)| (top, height))
        .collect::<Vec<_>>();
    assert_eq!(tops.len(), 2, "{drawn:?}");
    assert_eq!((tops[0].1, tops[1].1), (12, 12));
    assert_eq!(
        [a < tops[0].0, tops[0].0 < b, b < tops[1].0, tops[1].0 < c],
        [true; 4]
    );
}

#[test]
fn holds_the_room_of_a_border_in_the_box_of_the_line_next_to_it_where_the_target_does() {
    use crate::quirks::{BorderSpace, MultipleBaseline, SpaceBeforeAscent};
    let lay = |body: &str, rule: BorderSpace| {
        let target = crate::layout::testing::target_at(300, |p| {
            p.with_variant(rule)
                .with_variant(MultipleBaseline::DescentAboveExtra)
                .with_variant(SpaceBeforeAscent::RoundedApart)
        });
        let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
        ['a', 'c'].map(|c| at(&list, c).1)
    };
    // A paragraph of 1.5 lines between two plain ones, with a border of 3 pt and 2 pt of
    // space, or with the same 5 pt (100 twips) as its own space before or after.
    let body = |properties: &str| {
        format!(
            "{}<w:p><w:pPr>{properties}</w:pPr><w:r><w:t>a</w:t></w:r></w:p>{}",
            p("b"),
            p("c")
        )
    };
    let spacing = |space: &str| format!(r#"<w:spacing {space} w:line="360" w:lineRule="auto"/>"#);
    for (border, space) in [("top", r#"w:before="100""#), ("bottom", r#"w:after="100""#)] {
        let bordered = body(&format!(
            r#"<w:pBdr><w:{border} w:val="single" w:sz="24" w:space="2"/></w:pBdr>{}"#,
            spacing("")
        ));
        let spaced = lay(&body(&spacing(space)), BorderSpace::Outside);
        let held = lay(&bordered, BorderSpace::Held);
        let outside = lay(&bordered, BorderSpace::Outside);
        // Held, the border's room is the line's space: the line lies where it lies below or
        // above that space. Outside, it lies a dot off. The next paragraph does not move.
        assert_eq!(held, spaced, "{border}");
        assert_eq!((outside[0] - spaced[0]).abs(), 1, "{border}");
        assert_eq!(outside[1], held[1], "{border}");
    }
}

#[test]
fn puts_the_top_line_from_the_content_start_below_it_where_the_target_does() {
    use crate::quirks::TopBorderPlace;
    let lay = |side: &str, rule: TopBorderPlace| {
        let target = crate::layout::testing::target_at(300, |p| p.with_variant(rule));
        let body = format!(
            r#"<w:p><w:pPr><w:pBdr><w:top {side} w:space="2"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#
        );
        let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        let mut tops: Vec<i64> = rects(&list, 0).iter().map(|r| r.1).collect();
        tops.sort_unstable();
        (tops, at(&list, 'a'))
    };
    // The border starts at the margin, 72 pt or 300 dots of 0.24 pt. A line of 1 pt (4.17
    // dots) and 2 pt of space (8.33 dots) end at 75 pt, 312.5 dots, which round up to 313: less
    // 8 and 4 dots, the line's top lies at 301. Two lines of 0.5 pt (2.08 dots) with a gap
    // as wide end at 75.5 pt, 314.6 dots, up to 315: less 8 dots and three parts of 2 dots,
    // the first line lies at 301 and the second 4 dots below it.
    for (side, nearest, from_start) in [
        (r#"w:val="single" w:sz="8""#, vec![300], vec![301]),
        (r#"w:val="double" w:sz="4""#, vec![300, 304], vec![301, 305]),
    ] {
        let (tops, text) = lay(side, TopBorderPlace::Nearest);
        assert_eq!(tops, nearest, "{side}");
        let (moved, moved_text) = lay(side, TopBorderPlace::FromContentStart);
        assert_eq!(moved, from_start, "{side}");
        // The text below the border does not move.
        assert_eq!(moved_text, text, "{side}");
    }
}

#[test]
fn stops_the_fill_at_the_inner_edges_of_its_own_lines_where_the_target_does() {
    use crate::quirks::FillAtLines;
    // The fill, the tallest shape, and the lines above and below it from the top down, of a
    // shaded paragraph with lines on `sides`, in the body or in the header.
    let lay = |sides: &[&str], header: bool, rule: FillAtLines| {
        let target = crate::layout::testing::target_at(300, |p| p.with_variant(rule));
        let lines = sides.iter().fold(String::new(), |mut out, side| {
            let _ = write!(out, r#"<w:{side} w:val="single" w:sz="8" w:space="2"/>"#);
            out
        });
        let shaded = format!(
            r#"<w:p><w:pPr><w:pBdr>{lines}</w:pBdr><w:shd w:val="clear" w:color="auto" w:fill="DDEEFF"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#
        );
        let (body, story) = if header {
            (p("b"), Some(shaded.as_str()))
        } else {
            (shaded.clone(), None)
        };
        let list = pass_with(&body, (NORMAL, None), story, Numbering::default(), target).list;
        let mut shapes = rects(&list, 0);
        shapes.sort_unstable_by_key(|r| r.3);
        let fill = shapes.pop().unwrap();
        let mut lines = shapes;
        lines.sort_unstable_by_key(|r| r.1);
        (fill, lines)
    };
    // Lines of 1 pt (4 dots of 0.24 pt) with 2 pt of space above and below the text: inside
    // them, the fill starts at the top line's bottom and ends at the bottom line's top.
    let both: &[&str] = &["top", "bottom"];
    let (under, lines) = lay(both, false, FillAtLines::Under);
    let (top, bottom) = (lines[0], lines[1]);
    // Under them, it starts at the top line's top and ends past the bottom line's top.
    assert!(under.1 <= top.1 && under.1 + under.3 > bottom.1);
    let (inside, same) = lay(both, false, FillAtLines::Inside);
    assert_eq!(same, lines);
    assert_eq!(inside.1, top.1 + top.3);
    assert_eq!(inside.1 + inside.3, bottom.1);
    // A side without its own line keeps its place.
    let (under, _) = lay(&["top"], false, FillAtLines::Under);
    let (inside, lines) = lay(&["top"], false, FillAtLines::Inside);
    assert_eq!(inside.1, lines[0].1 + lines[0].3);
    assert_eq!(inside.1 + inside.3, under.1 + under.3);
    // In a header, the fill stays under the lines.
    assert_eq!(
        lay(both, true, FillAtLines::Inside),
        lay(both, true, FillAtLines::Under)
    );
}

/// The tops of the border lines of a paragraph with `props` and the text "h" of `size` half
/// points, with a top line and a bottom line of 0.75 pt with 3 pt of space, in the body or in
/// the header, under `edge`, and the place of the text.
fn text_edge_lines(
    edge: crate::quirks::BorderTextEdge,
    (size, props): (u32, &str),
    in_header: bool,
) -> (Vec<i64>, (i64, i64)) {
    let target = crate::layout::testing::target_at(300, |p| {
        p.with_variant(edge)
            .with_variant(crate::quirks::TopBorderPlace::FromContentStart)
    });
    let line = r#"w:val="single" w:sz="6" w:space="3""#;
    let bordered = format!(
        r#"<w:p><w:pPr><w:pBdr><w:top {line}/><w:bottom {line}/></w:pBdr>{props}<w:rPr><w:sz w:val="{size}"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="{size}"/></w:rPr><w:t>h</w:t></w:r></w:p>"#
    );
    let (body, header) = if in_header {
        (p("a"), Some(bordered.as_str()))
    } else {
        (bordered.clone(), None)
    };
    let list = pass_with(&body, (NORMAL, None), header, Numbering::default(), target).list;
    let mut tops: Vec<i64> = rects(&list, 0).iter().map(|r| r.1).collect();
    tops.sort_unstable();
    (tops, at(&list, 'h'))
}

#[test]
fn places_border_lines_from_the_rounded_text_edge_where_the_target_does() {
    use crate::quirks::BorderTextEdge::{Exact, Rounded};
    // In dots of 0.24 pt, the border's width and space are 3.125 and 12.5, 15.625 together,
    // 16 rounded. The text of the fake font at 11 pt ascends 36.667 dots and descends 9.167,
    // 37 and 9 rounded, on a line of 45.833: 15.625 + 45.833 rounds to 61, and 61 - 37 - 9 = 15
    // is less than 16. The top line's text edge lies 15 dots below the place before the
    // border, the body's top at 300, and the line its 3 dots and the space's 12 above it, at
    // 300. The content start, 315.625 rounded up, puts it at 301. The bottom line lies 12 dots
    // below the text edge, 15 dots above the rounded outer edge 300 + 15.625 + 45.833 +
    // 15.625 = 377.083: at 374, which the nearest dot below the space gives too.
    let single = (22, "");
    let (rounded, text) = text_edge_lines(Rounded, single, false);
    assert_eq!(rounded, [300, 374]);
    let (exact, exact_text) = text_edge_lines(Exact, single, false);
    assert_eq!(exact, [301, 374]);
    assert_eq!(text, exact_text);
    // At 10 pt, 33.333 and 8.333 dots, 33 and 8 rounded, on a line of 41.667: 57 - 41 = 16, so
    // both edges lie 16 dots inside the outer edges. The bottom line lies at 373 - 16 + 12 =
    // 369; the nearest dot below the space, 357.292 + 12.5, is 370.
    let (rounded, text) = text_edge_lines(Rounded, (20, ""), false);
    assert_eq!(rounded, [301, 369]);
    let (exact, exact_text) = text_edge_lines(Exact, (20, ""), false);
    assert_eq!(exact, [301, 370]);
    assert_eq!(text, exact_text);
}

#[test]
fn places_an_at_least_top_line_from_the_rounded_text_edge_in_a_header() {
    use crate::quirks::BorderTextEdge::{Exact, Rounded};
    // A minimum of 16.5 pt, 68.75 dots, gives the 10 pt line 27.083 dots of extra room. The
    // border's room with it, 42.708, rounds to 43, and the line's height with the room, 84.375,
    // to 84, less 33 and 8: 43. The header's place before the border is 150, so the text edge
    // lies at 193 and the top line at 193 - 15 = 178. On the text's single line, the baseline
    // 150 + 76.042 rounded less 48.958 rounded puts it at 177.
    let least = (20, r#"<w:spacing w:line="330" w:lineRule="atLeast"/>"#);
    let (rounded, text) = text_edge_lines(Rounded, least, true);
    assert_eq!(rounded[0], 178);
    let (exact, exact_text) = text_edge_lines(Exact, least, true);
    assert_ne!(exact[0], rounded[0]);
    // The text's line does not move.
    assert_eq!(text, exact_text);
}

/// The top of the bottom border line of 0.75 pt with 3 pt of space of a paragraph of the text
/// "h" at 11 pt and the automatic spacing `line`, under `rule`, and the place of the text.
fn multiple_bottom_line(
    rule: crate::quirks::MultipleBottomBorder,
    line: u32,
) -> (Vec<i64>, (i64, i64)) {
    let target = crate::layout::testing::target_at(300, |p| p.with_variant(rule));
    let body = format!(
        r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="3"/></w:pBdr><w:spacing w:line="{line}" w:lineRule="auto"/><w:rPr><w:sz w:val="22"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>h</w:t></w:r></w:p>"#
    );
    let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    let tops = rects(&list, 0).iter().map(|r| r.1).collect();
    (tops, at(&list, 'h'))
}

/// The tops of the bottom border line of a one-line paragraph of the fake font at 11 pt with the
/// spacing `spacing` (the attributes of its `w:spacing`), below a plain line and above another,
/// on the test target at 300 dots that `change` makes.
fn spaced_bottom_line(
    change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
    spacing: &str,
) -> Vec<i64> {
    let target = crate::layout::testing::target_at(300, change);
    let body = format!(
        r#"<w:p><w:pPr><w:spacing w:after="0"/><w:rPr><w:sz w:val="22"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>a</w:t></w:r></w:p><w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="3"/></w:pBdr><w:spacing {spacing}/><w:rPr><w:sz w:val="22"/></w:rPr></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>h</w:t></w:r></w:p>{}"#,
        p("n")
    );
    let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    rects(&list, 0).iter().map(|r| r.1).collect()
}

/// The tops of the bottom border line of a one-line paragraph of 1.4 lines with the space after
/// `after` in twips, below a plain line and above another, under `rule`.
fn spaced_multiple_bottom_line(rule: crate::quirks::MultipleBottomBorder, after: u32) -> Vec<i64> {
    spaced_bottom_line(
        |p| p.with_variant(rule),
        &format!(r#"w:after="{after}" w:line="336" w:lineRule="auto""#),
    )
}

/// The tops of the bottom border line of a one-line paragraph of single spacing with the space
/// after `after` in twips, below a plain line and above another, from the rounded text edge with
/// the space after's part `joined`.
fn spaced_single_bottom_line(
    joined: crate::quirks::BottomBorderSpaceAfter,
    after: u32,
) -> Vec<i64> {
    spaced_bottom_line(
        |p| {
            p.with_variant(crate::quirks::BorderTextEdge::Rounded)
                .with_variant(joined)
        },
        &format!(r#"w:after="{after}""#),
    )
}

#[test]
fn joins_the_space_after_to_the_room_of_the_bottom_line_of_single_spacing_where_the_target_does() {
    use crate::quirks::BottomBorderSpaceAfter::{Apart, Joined};
    // In dots of 0.24 pt, the bordered line of the fake font at 11 pt below a single line
    // starts at 345.833 and its box ends at 391.667, its ascent 36.667 and descent 9.167
    // rounding to 37 and 9. Apart, the outer edge 407.292 rounds to 407 and the room is the
    // smaller of 15.625 rounded, 16, and 61.458 rounded less 37 and 9, 15: the text edge lies at
    // 392 and the line its space's 12 dots below it, at 404. A space after of 12.5 pt, 52.083
    // dots, joined to the border's width and space, 67.708 together: the outer edge 459.375
    // rounds to 459, and the room is 67.708 rounded, 68, and 113.542 rounded less 37 and 9, also
    // 68; the text edge lies at 391 and the line at 403.
    assert_eq!(spaced_single_bottom_line(Apart, 250), [404]);
    assert_eq!(spaced_single_bottom_line(Joined, 250), [403]);
    assert_eq!(spaced_single_bottom_line(Joined, 0), [404]);
}

#[test]
fn joins_the_space_after_to_the_room_of_the_bottom_line_of_multiple_spacing() {
    use crate::quirks::MultipleBottomBorder::FromTextEdge;
    // In dots of 0.24 pt, the bordered line of 1.4 lines below a single line of the fake font
    // at 11 pt starts at 345.833 and its box ends at 410. Without a space after, the outer edge
    // 425.625 rounds to 426 and the room is 16: the text edge lies at 410 and the line its
    // space's 12 dots below it, at 422. A space after of 5 pt, 20.833 dots, joins the border's
    // width and space, 36.458 together: the outer edge 446.458 rounds to 446, and the room is
    // 54.792 rounded less 18, 37, and 100.625 rounded less 37, 9 and 18, also 37; the text edge
    // lies at 409 and the line at 421.
    assert_eq!(spaced_multiple_bottom_line(FromTextEdge, 0), [422]);
    assert_eq!(spaced_multiple_bottom_line(FromTextEdge, 100), [421]);
}

#[test]
fn places_the_bottom_line_of_multiple_spacing_from_the_rounded_text_edge_where_the_target_does() {
    use crate::quirks::MultipleBottomBorder::{FromTextEdge, Nearest};
    // In dots of 0.24 pt, 1.4 lines of the fake font at 11 pt are 64.167 dots, 18.333 more
    // than its ascent of 36.667 and descent of 9.167: the box of the line from the body's top
    // at 300 ends at 364.167. The border's width and space are 3.125 and 12.5, 15.625
    // together. The nearest dot below the space, 376.667, is 377. From the rounded text edge,
    // the outer edge 379.792 rounds to 380; the room is 33.958 rounded less 18.333 rounded,
    // 34 - 18 = 16, and 79.792 rounded less 37, 9 and 18, also 16; the text edge lies at 364
    // and the line its space's 12 dots below it, at 376.
    let (nearest, text) = multiple_bottom_line(Nearest, 336);
    assert_eq!(nearest, [377]);
    let (rounded, rounded_text) = multiple_bottom_line(FromTextEdge, 336);
    assert_eq!(rounded, [376]);
    // The text's line does not move.
    assert_eq!(text, rounded_text);
    // Below single spacing the line keeps the nearest dot.
    assert_eq!(
        multiple_bottom_line(FromTextEdge, 216).0,
        multiple_bottom_line(Nearest, 216).0
    );
}

#[test]
fn keeps_the_top_line_of_a_header_paragraph_on_its_nearest_dot() {
    use crate::quirks::TopBorderPlace;
    let lay = |rule: TopBorderPlace| {
        let target = crate::layout::testing::target_at(300, |p| p.with_variant(rule));
        let header = r#"<w:p><w:pPr><w:pBdr><w:top w:val="single" w:sz="8" w:space="2"/></w:pBdr></w:pPr><w:r><w:t>h</w:t></w:r></w:p>"#;
        let list = pass_with(
            p("a").as_str(),
            (NORMAL, None),
            Some(header),
            Numbering::default(),
            target,
        )
        .list;
        rects(&list, 0).iter().map(|r| r.1).collect::<Vec<i64>>()
    };
    // The header starts 36 pt or 150 dots down the page. In the body, a line of 1 pt with 2 pt
    // of space would lie at dot 151; in a header it stays at the nearest dot, 150.
    assert_eq!(lay(TopBorderPlace::FromContentStart), vec![150]);
    assert_eq!(lay(TopBorderPlace::Nearest), vec![150]);
}

#[test]
fn cuts_the_width_of_a_border_to_whole_twips_where_the_target_does() {
    // Top borders of 3 and 25 eighths, and of 6 eighths in a medium gap style, on a device of
    // 600 dots an inch, where a dot is 0.12 pt.
    let boxed = |style: &str, eighths: u32| {
        format!(
            r#"<w:p><w:pPr><w:pBdr><w:top w:val="{style}" w:sz="{eighths}"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>{}"#,
            p("b")
        )
    };
    let body = [
        boxed("single", 3),
        boxed("single", 25),
        boxed("thinThickMediumGap", 6),
    ]
    .concat();
    let lay = |unit| {
        let target = crate::layout::testing::target_at(600, |p| p.with_variant(unit));
        let dot = target.0.dots(1).units();
        let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        // The height of each line in dots of the device.
        list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| {
                if let Item::Rect(rect) = item {
                    Some(rect.height.units() / dot)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    };
    // In eighths, 3 eighths are 3.125 dots and 25 eighths 26.04, rounded down to 3 and 26. In
    // whole twips, 7.5 and 62.5 twips are 7 and 62, 2.92 and 25.83 dots, so 2 and 25. The
    // medium gap style's thick line of 6 eighths is 15 twips in both, and its thin line, half
    // of it, 3.125 dots: cut on its own it would be 7 twips and 2 dots.
    assert_eq!(lay(BorderWidthUnit::EighthPoints), [3, 26, 6, 3]);
    assert_eq!(lay(BorderWidthUnit::WholeTwips), [2, 25, 6, 3]);
}

#[test]
fn drops_the_border_of_the_empty_paragraph_that_ends_a_section_where_the_target_does() {
    // A bottom line on the empty paragraph that ends the first section, on an empty paragraph
    // that ends none, and on a paragraph with text that ends the second section. Each section
    // starts on a new page.
    let bottom = r#"<w:pBdr><w:bottom w:val="single" w:sz="4" w:space="1"/></w:pBdr>"#;
    let body = format!(
        "{}<w:p><w:pPr>{bottom}<w:sectPr/></w:pPr></w:p><w:p><w:pPr>{bottom}</w:pPr></w:p>{}<w:p><w:pPr>{bottom}<w:sectPr/></w:pPr><w:r><w:t>c</w:t></w:r></w:p>{}<w:sectPr/>",
        p("a"),
        p("b"),
        p("d")
    );
    let lay = |rule| {
        let target = on_base_with(|p| p.with_variant(rule));
        let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        (0..list.pages().len())
            .map(|page| rects(&list, page).len())
            .collect::<Vec<_>>()
    };
    // The lines of each page: the first section's end on page 1, and the two paragraphs of the
    // second section on page 2. Only the line of the empty paragraph that ends a section goes.
    assert_eq!(lay(SectionEndBorders::Drawn), [1, 2, 0]);
    assert_eq!(lay(SectionEndBorders::Dropped), [0, 2, 0]);
}

#[test]
fn stacks_the_lines_of_a_compound_bottom_border_in_whole_dots_where_the_target_does() {
    // A double bottom border of 0.875 pt: three parts of 3.65 dots each of the test device.
    let body = r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="double" w:sz="7" w:space="1"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let lay = |rule| {
        let target = on_base_with(|p| p.with_variant(rule));
        let dot = target.0.dots(1).units();
        let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
        let mut lines: Vec<(i64, i64)> = list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Rect(r) => Some((r.y.units() / dot, r.height.units() / dot)),
                _ => None,
            })
            .collect();
        lines.sort_unstable();
        (
            lines[0].0,
            lines[1].0 - lines[0].0,
            (lines[0].1, lines[1].1),
        )
    };
    let (first, gap, heights) = lay(BottomBorderParts::Stacked);
    // Stacked, the second line lies the first line and the gap below the first, each rounded
    // down to 3 dots; each line is 3 dots thick.
    assert_eq!((gap, heights), (6, (3, 3)));
    // At its own offset of 7.29 dots, rounded to the nearest dot, the second line lies 7 or 8
    // dots below the first, which stays where it was.
    let (nearest_first, nearest_gap, nearest_heights) = lay(BottomBorderParts::Nearest);
    assert_eq!((nearest_first, nearest_heights), (first, heights));
    assert!(nearest_gap == 7 || nearest_gap == 8, "{nearest_gap}");
}

#[test]
fn keeps_the_fill_of_a_bottom_side_without_a_line_where_the_target_stacks_the_lines() {
    use crate::quirks::FillAtLines;
    // A shaded paragraph whose bottom side of none keeps its 3 pt of space, 12.5 dots, inside
    // which the fill ends.
    let body = r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="none" w:sz="0" w:space="3"/></w:pBdr><w:shd w:val="clear" w:color="auto" w:fill="DDEEFF"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let lay = |rule| {
        let target = crate::layout::testing::target_at(300, |p| {
            p.with_variant(NoneBorders::KeepSpace)
                .with_variant(FillAtLines::Inside)
                .with_variant(rule)
        });
        let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
        list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Rect(r) => Some((r.y.units(), r.height.units())),
                _ => None,
            })
            .collect::<Vec<_>>()
    };
    // The side has no line to stack, so the fill ends at the same place, off the dots.
    let nearest = lay(BottomBorderParts::Nearest);
    assert_eq!(nearest.len(), 1);
    assert_eq!(lay(BottomBorderParts::Stacked), nearest);
}

#[test]
fn border_groups_split_when_outer_indents_differ_and_merge_when_they_match() {
    let bdr = r#"<w:pBdr><w:top w:val="single" w:sz="12" w:space="2"/><w:bottom w:val="single" w:sz="12" w:space="2"/></w:pBdr>"#;
    let second_y = |ind1: &str, ind2: &str| {
        let body = format!(
            "<w:p><w:pPr>{bdr}{ind1}</w:pPr><w:r><w:t>a</w:t></w:r></w:p><w:p><w:pPr>{bdr}{ind2}</w:pPr><w:r><w:t>b</w:t></w:r></w:p>"
        );
        let list = lay_out(&body, NORMAL, None);
        at(&list, 'b').1
    };
    let merged = second_y("", "");
    // Positive firstLine indent and matching outer edge (left=360 vs left=720 hanging=360) merge.
    assert_eq!(second_y("", r#"<w:ind w:firstLine="360"/>"#), merged);
    assert_eq!(
        second_y(
            r#"<w:ind w:left="360"/>"#,
            r#"<w:ind w:left="720" w:hanging="360"/>"#
        ),
        merged
    );
    // Differing outer left or right edges split the group, adding bottom + top border rooms.
    let split_left = second_y("", r#"<w:ind w:left="720"/>"#);
    let split_right = second_y("", r#"<w:ind w:right="720"/>"#);
    let split_hanging = second_y("", r#"<w:ind w:left="720" w:hanging="360"/>"#);
    assert!(split_left > merged);
    assert_eq!(split_right, split_left);
    assert_eq!(split_hanging, split_left);
}