f-office-docx 0.1.0

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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
//! Drawings that float: their places in their areas, and the wraps that the lines of the body
//! go round, on the page of their anchor or of the header.

use f_office_paint::DisplayList;
use f_office_units::Length;
use f_office_warnings::Name;

use super::{Size, areas, place};
use crate::body::{Section, Sections};
use crate::chart::{Chart, Columns, Title};
use crate::floating::{Floating, PageArea, Position, Relative};
use crate::layout::testing::{
    AnchoredShape, Fake, NORMAL, SQUARE_WRAP, ShapeText, base_context, du, filler, find, find_all,
    kept, lay_out_with_header, on_base, on_base_with, p, pages, pass_with, pass_with_header,
    passes, shape_top, x_du,
};
use crate::layout::{Layout, SectionLayout};
use crate::numbering::Numbering;
use crate::props::Align;
use crate::quirks::{
    BlockedLines, BoxLastLine, BoxOutlineLeft, BoxTextTop, LineWrapBand, PolygonWrap, StepEnd,
    VmlBoxOutline,
};
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::text::{Shaper, ShaperSettings};
use crate::{Drawing, Reason, Warning};

fn units(units: i64) -> Length {
    Length::from_units(units)
}

#[test]
fn places_drawings_in_their_areas() {
    let page = areas(units(1000), units(100), units(50));
    let span = |start, end| (units(start), units(end));
    assert_eq!(
        (page.page, page.text, page.start_margin, page.end_margin),
        (span(0, 1000), span(100, 950), span(0, 100), span(950, 1000))
    );
    let at = |from, offset, align: Option<Align>| {
        let position = Position {
            from,
            offset: units(offset),
            align,
            share: None,
        };
        place(
            position,
            (units(20), Length::ZERO, Length::ZERO),
            Length::ZERO,
            &page,
            units(300),
        )
    };
    // A share of the area wins over the offset: 4.5% of the page, and 10% of the margins.
    // A share whose part of the area does not fit in a length places by the offset.
    let share = |from, share| Position {
        from,
        offset: units(7),
        align: None,
        share: Some(share),
    };
    let sized = (units(20), Length::ZERO, Length::ZERO);
    let shared = |from, value| place(share(from, value), sized, Length::ZERO, &page, units(300));
    assert_eq!(shared(Relative::Area(PageArea::Page), 4_500), units(45));
    assert_eq!(shared(Relative::Area(PageArea::Margin), 10_000), units(185));
    assert_eq!(shared(Relative::Area(PageArea::Page), i64::MAX), units(7));
    let cases = [
        (Relative::Area(PageArea::Page), 30, None, 30),
        (Relative::Area(PageArea::Margin), 30, None, 130),
        (Relative::Area(PageArea::Margin), 0, Some(Align::Start), 100),
        (
            Relative::Area(PageArea::Margin),
            0,
            Some(Align::Center),
            515,
        ),
        (Relative::Area(PageArea::Margin), 0, Some(Align::End), 930),
        (
            Relative::Area(PageArea::StartMargin),
            0,
            Some(Align::Center),
            40,
        ),
        (
            Relative::Area(PageArea::EndMargin),
            0,
            Some(Align::End),
            980,
        ),
        (Relative::Area(PageArea::EndMargin), 7, None, 957),
        (Relative::Paragraph, 30, None, 330),
        (Relative::Paragraph, 0, Some(Align::End), 300),
    ];
    for (from, offset, align, expected) in cases {
        assert_eq!(
            at(from, offset, align),
            units(expected),
            "{from:?} {offset} {align:?}"
        );
    }
}

#[test]
fn aligns_a_drawing_with_its_effect_extent() {
    let page = areas(units(1000), units(100), units(50));
    // An effect extent of 4 at the left and 10 at the right aligns with the box: the box
    // starts 4 in, ends 10 short of the end, and is centered with them.
    let aligned = |align| Position {
        from: Relative::Area(PageArea::Margin),
        offset: Length::ZERO,
        align: Some(align),
        share: None,
    };
    let effect = (units(20), units(4), units(10));
    let at = |align| place(aligned(align), effect, Length::ZERO, &page, units(300));
    assert_eq!(at(Align::Start), units(104));
    assert_eq!(at(Align::End), units(920));
    assert_eq!(at(Align::Center), units(512));
}

#[test]
fn breaks_a_line_that_goes_to_the_next_page_beside_the_headers_drawing() {
    // A box with square wrap in the header, from 306 pt to 450 pt across and from the top
    // margin down half an inch: the body lines at the top of each page go round it, left of
    // it and on right of it.
    let shape = AnchoredShape {
        across: ("page", 3_886_200),
        down: ("page", 914_400),
        size: (1_828_800, 457_200),
        wrap: SQUARE_WRAP,
        outline: None,
        text: None,
    };
    let header = format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing());
    // The filler ends page 1, so the long paragraph starts at the top of page 2.
    let words = vec!["zz"; 80].join(" ");
    let body = filler(64) + &p(&words);
    let list = lay_out_with_header(&body, NORMAL, None, Some(&header));
    let on_two: Vec<(usize, i64, i64)> = find_all(&list, 'z')
        .into_iter()
        .filter(|g| g.0 == 1)
        .collect();
    let first = on_two.iter().map(|g| g.2).min().unwrap();
    let point = f_office_units::Length::from_points(1).unwrap().units();
    let line: Vec<i64> = on_two
        .iter()
        .filter(|g| g.2 == first)
        .map(|g| g.1)
        .collect();
    assert!(line.iter().any(|&x| x < 306 * point));
    assert!(line.iter().any(|&x| x >= 450 * point));
    assert!(
        !line
            .iter()
            .any(|&x| (306 * point..450 * point).contains(&x))
    );
}

/// Lines of exact 18 pt, of which 36 fill the body of 648 pt.
const EXACT_18: &str = r#"<w:pPr><w:spacing w:line="360" w:lineRule="exact"/></w:pPr>"#;

/// A body for the wraps that move their anchor: `lines` paragraphs of 59 glyphs, which take
/// one line of the body and two lines in its left half; then the paragraph "x", which anchors
/// a box with the wrap element `wrap`, 234 pt wide and 72 pt high at the top of the body's
/// right half, measured from the page; then the paragraph "y".
fn body_with_a_box_at_the_page_top(lines: usize, wrap: &str) -> String {
    let words = ["qqqq"; 12].join(" ");
    let text = |text: &str| format!("<w:p>{EXACT_18}<w:r><w:t>{text}</w:t></w:r></w:p>");
    let shape = AnchoredShape {
        across: ("page", 3_886_200),
        down: ("page", 914_400),
        size: (2_971_800, 914_400),
        wrap,
        outline: None,
        text: None,
    };
    let anchor = format!(
        "<w:p>{EXACT_18}<w:r>{}</w:r><w:r><w:t>x</w:t></w:r></w:p>",
        shape.drawing()
    );
    (0..lines).map(|_| text(&words)).collect::<String>() + &anchor + &text("y")
}

/// The number of lines with the glyph `ch` on the page `page`.
fn lines_on(list: &DisplayList, ch: char, page: usize) -> usize {
    let mut lines: Vec<i64> = find_all(list, ch)
        .iter()
        .filter(|g| g.0 == page)
        .map(|g| g.2)
        .collect();
    lines.sort_unstable();
    lines.dedup();
    lines.len()
}

#[test]
fn keeps_the_wrap_of_a_box_whose_anchor_stays_on_its_page() {
    // 33 paragraphs take 35 lines beside the box, and the anchor is line 36.
    let pass = passes(&body_with_a_box_at_the_page_top(33, SQUARE_WRAP));
    assert_eq!(lines_on(&pass.list, 'q', 0), 35);
    assert_eq!((find(&pass.list, 'x').0, find(&pass.list, 'y').0), (0, 1));
    assert_eq!(pass.wraps.pages().collect::<Vec<_>>(), [0]);
}

#[test]
fn moves_a_box_whose_wrap_pushes_its_anchor_off_the_page() {
    // 34 paragraphs take 36 lines beside the box, so the anchor has no room on the page. The
    // anchor and the box go to the next page, and the first page has no wrap: 34 lines. The
    // anchor does not go back to the room that the first page now has.
    for lines in [34, 35] {
        let pass = passes(&body_with_a_box_at_the_page_top(lines, SQUARE_WRAP));
        assert_eq!(lines_on(&pass.list, 'q', 0), lines);
        let (x, y) = (find(&pass.list, 'x'), find(&pass.list, 'y'));
        // "x" starts the next page, and "y" is the line below it, beside the box.
        assert_eq!((x.0, y.0), (1, 1));
        assert_eq!(y.2 - x.2, du(360));
        assert!(y.1 < 306 * f_office_units::Length::UNITS_PER_POINT);
        assert_eq!(pass.wraps.pages().collect::<Vec<_>>(), [1]);
    }
}

#[test]
fn moves_a_box_with_top_and_bottom_wrap_that_pushes_its_anchor_off_the_page() {
    // The box moves the lines down by four. With 30 paragraphs the anchor is line 35.
    const BAND: &str = "<wp:wrapTopAndBottom/>";
    let pass = passes(&body_with_a_box_at_the_page_top(30, BAND));
    let (below, x) = (find(&pass.list, 'q'), find(&pass.list, 'x'));
    assert_eq!((x.0, x.2 - below.2), (0, du(30 * 360)));
    // With 34 paragraphs it has no room: the first page has no wrap, so its first line lies
    // four lines higher, and the next page has the box and the anchor below it, on line 5.
    let pass = passes(&body_with_a_box_at_the_page_top(34, BAND));
    let top = find(&pass.list, 'q');
    assert_eq!(below.2 - top.2, du(4 * 360));
    let (x, y) = (find(&pass.list, 'x'), find(&pass.list, 'y'));
    assert_eq!((x.0, y.0), (1, 1));
    assert_eq!((x.2 - top.2, y.2 - top.2), (du(4 * 360), du(5 * 360)));
}

/// The baseline of the line "x" of a paragraph that anchors two boxes of the wrap `wrap` at
/// the left of the page: the first one 20 pt below the top margin and 20 pt high, and the
/// second one at the top margin and 18 pt high, one line of the paragraph.
fn line_below_two_boxes(wrap: &str) -> i64 {
    let shape = |down: i64, height: i64| {
        AnchoredShape {
            across: ("page", 0),
            down: ("page", down),
            size: (1_270_000, height),
            wrap,
            outline: None,
            text: None,
        }
        .drawing()
    };
    // 72 pt, the top margin, and 20 pt are 914,400 and 254,000 EMU; 18 pt are 228,600.
    let (lower, upper) = (shape(1_168_400, 254_000), shape(914_400, 228_600));
    let body =
        format!("<w:p>{EXACT_18}<w:r>{lower}</w:r><w:r>{upper}</w:r><w:r><w:t>x</w:t></w:r></w:p>");
    find(&passes(&body).list, 'x').2
}

#[test]
fn moves_a_line_below_a_band_that_its_move_below_a_later_band_takes_it_into() {
    // The line at the top margin runs into the band of the second box and goes below it, 18 pt
    // down, where it runs into the band of the first box, which the list holds before the
    // second. It goes below that one too: 40 pt down.
    let free = line_below_two_boxes("<wp:wrapNone/>");
    let below = line_below_two_boxes("<wp:wrapTopAndBottom/>");
    assert_eq!(below - free, du(40 * 20));
}

#[test]
fn takes_the_drawings_of_a_paragraph_to_the_page_of_its_first_line() {
    // 36 lines fill the page, so the anchor paragraph starts the next page, and its box lies
    // there, also in the first pass.
    let body = body_with_a_box_at_the_page_top(36, SQUARE_WRAP);
    let first = pass_with_header(&body, NORMAL, None, None);
    assert_eq!(first.wraps.pages().collect::<Vec<_>>(), [1]);
    let pass = passes(&body);
    assert_eq!(lines_on(&pass.list, 'q', 0), 36);
    assert_eq!((find(&pass.list, 'x').0, find(&pass.list, 'y').0), (1, 1));
}

/// The run of a text box without insets and without wrap that holds the line "b", 24 pt below
/// its paragraph and 330 pt from the page's left edge.
fn box_below_its_paragraph() -> String {
    let shape = AnchoredShape {
        across: ("page", 4_191_000),
        down: ("paragraph", 304_800),
        size: (1_905_000, 457_200),
        wrap: "<wp:wrapNone/>",
        outline: None,
        text: Some(ShapeText {
            blocks: "<w:p><w:r><w:t>b</w:t></w:r></w:p>",
            body: r#"<wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="0"/>"#,
        }),
    };
    format!("<w:r>{}</w:r>", shape.drawing())
}

/// `fill` paragraphs of one line of exactly 18 pt, then a paragraph of exact lines without
/// widow control that holds `runs`, then the paragraph "y".
fn after_lines(fill: usize, runs: &str) -> String {
    const FREE: &str =
        r#"<w:pPr><w:widowControl w:val="0"/><w:spacing w:line="360" w:lineRule="exact"/></w:pPr>"#;
    let line = |text: &str| format!("<w:p>{EXACT_18}<w:r><w:t>{text}</w:t></w:r></w:p>");
    let filler: String = (0..fill).map(|_| line("q")).collect();
    filler + &format!("<w:p>{FREE}{runs}</w:p>") + &line("y")
}

/// The page and the baseline of the box's line "b" and of the line "d", in a layout of `body`
/// in passes.
fn box_and_line(body: &str) -> ((usize, i64), (usize, i64)) {
    let list = passes(body).list;
    let ((b_page, _, b), (d_page, _, d)) = (find(&list, 'b'), find(&list, 'd'));
    ((b_page, b), (d_page, d))
}

#[test]
fn places_a_drawing_from_the_part_of_its_paragraph_on_the_page_of_its_anchor() {
    // The paragraph alone: the box lies 24 pt below its top, at the top of the page.
    let alone = box_and_line(&after_lines(
        0,
        &(box_below_its_paragraph() + "<w:r><w:t>d</w:t></w:r>"),
    ));
    assert_eq!((alone.0.0, alone.1.0), (0, 0));
    // After 34 lines, "a" and "c" end the page and "d", whose run the box's run comes right
    // before, starts the next one. The box lies 24 pt below the top of the paragraph's part
    // there, where it lies when the paragraph starts that page, not below the paragraph's top
    // on the page before.
    let runs = "<w:r><w:t>a</w:t><w:br/><w:t>c</w:t><w:br/></w:r>".to_owned()
        + &box_below_its_paragraph()
        + "<w:r><w:t>d</w:t></w:r>";
    let ((b_page, b), (d_page, d)) = box_and_line(&after_lines(34, &runs));
    assert_eq!((b_page, d_page), (1, 1));
    assert_eq!((b, d), (alone.0.1, alone.1.1));
    // With the box's run before "a", the box stays 24 pt below the paragraph's top.
    let runs =
        box_below_its_paragraph() + "<w:r><w:t>a</w:t><w:br/><w:t>c</w:t><w:br/><w:t>d</w:t></w:r>";
    let ((b_page, b), _) = box_and_line(&after_lines(34, &runs));
    assert_eq!(b_page, 0);
    assert_eq!(b - alone.0.1, du(34 * 360));
}

#[test]
fn keeps_a_leading_page_break_on_a_full_page_before_a_drawing_anchored_after_it() {
    // 36 lines fill the page. The paragraph starts with a page break, which stays on that page
    // without room, and the box anchored after the break lies on the next page with "d", as
    // when the paragraph starts that page.
    let alone = box_and_line(&after_lines(
        0,
        &(box_below_its_paragraph() + "<w:r><w:t>d</w:t></w:r>"),
    ));
    let runs = r#"<w:r><w:br w:type="page"/></w:r>"#.to_owned()
        + &box_below_its_paragraph()
        + "<w:r><w:t>d</w:t></w:r>";
    let ((b_page, b), (d_page, d)) = box_and_line(&after_lines(36, &runs));
    assert_eq!((b_page, d_page), (1, 1));
    assert_eq!((b, d), (alone.0.1, alone.1.1));
}

/// A paragraph that anchors a box as wide as the column, `lines` lines high, one line below
/// the paragraph's top, with square wrap and no distances.
fn above_a_wide_box(lines: i64) -> String {
    let line = 127_000;
    let shape = AnchoredShape {
        across: ("column", 0),
        down: ("paragraph", line),
        size: (5_943_600, lines * line),
        wrap: SQUARE_WRAP,
        outline: None,
        text: None,
    };
    format!("<w:p><w:r>{}<w:t>d</w:t></w:r></w:p>", shape.drawing())
}

#[test]
fn tests_a_chain_below_a_drawing_that_leaves_no_room_beside_it() {
    // The anchor's line is the page's line 41, and the box takes the lines below it. Below
    // a box of 21 lines, the two kept paragraphs fill the page, and the paragraph after them
    // does not fit, so the chain starts the next page.
    let chain = kept("e") + &kept("h") + &p("z");
    let body = filler(40) + &above_a_wide_box(21) + &chain;
    assert_eq!(pages(&body, NORMAL, "dehz"), [0, 1, 1, 1]);
    // Below a box of 20 lines, the chain and its next paragraph fit.
    let body = filler(40) + &above_a_wide_box(20) + &chain;
    assert_eq!(pages(&body, NORMAL, "dehz"), [0, 0, 0, 0]);
}

/// A paragraph "x" of exact 18 pt lines that anchors a box as wide as the page, 30 pt high at
/// the paragraph's top, with the wrap element `wrap` and no distances, then the paragraph "y".
fn blocked_by_a_wide_box(wrap: &str, spacing: &str, height: i64) -> String {
    let shape = AnchoredShape {
        across: ("page", 0),
        down: ("paragraph", 0),
        size: (7_772_400, height),
        wrap,
        outline: None,
        text: None,
    };
    let x = format!(
        "<w:p>{spacing}<w:r>{}</w:r><w:r><w:t>x</w:t></w:r></w:p>",
        shape.drawing()
    );
    x + &format!("<w:p>{spacing}<w:r><w:t>y</w:t></w:r></w:p>")
}

/// A through wrap whose polygon is the box's bounds.
const THROUGH: &str = r#"<wp:wrapThrough wrapText="bothSides"><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapThrough>"#;

/// The baselines in device dots of the lines "x" and "y" of [`blocked_by_a_wide_box`] with a
/// box of `height` EMU under `blocked`.
fn blocked_baselines(
    (wrap, spacing, height): (&str, &str, i64),
    blocked: BlockedLines,
) -> (i64, i64) {
    let target = on_base_with(|p| p.with_variant(blocked));
    let body = blocked_by_a_wide_box(wrap, spacing, height);
    let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
    (find(&pass.list, 'x').2, find(&pass.list, 'y').2)
}

#[test]
fn moves_a_line_without_room_beside_a_polygon_wrap_in_steps_of_its_height() {
    // The box covers the line's first 30 pt. Below the box the line starts 30 pt down; in steps
    // of its 18 pt it starts 36 pt down. A square wrap keeps the line below the box under both.
    let top = |wrap: &str, blocked: BlockedLines| {
        let (x, y) = blocked_baselines((wrap, EXACT_18, 381_000), blocked);
        assert_eq!(y - x, du(360));
        x
    };
    let below = top(THROUGH, BlockedLines::BelowBox);
    assert_eq!(top(THROUGH, BlockedLines::LineSteps) - below, du(120));
    assert_eq!(top(SQUARE_WRAP, BlockedLines::LineSteps), below);
    assert_eq!(top(SQUARE_WRAP, BlockedLines::BelowBox), below);
}

/// A through wrap whose polygon covers the box's whole width in its top half and only its right
/// half below, so that its outline leaves the left of the bottom half free.
const THROUGH_OPEN_BOTTOM: &str = r#"<wp:wrapThrough wrapText="bothSides"><wp:wrapPolygon edited="1"><wp:start x="0" y="0"/><wp:lineTo x="0" y="10800"/><wp:lineTo x="10800" y="10800"/><wp:lineTo x="10800" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="0" y="0"/></wp:wrapPolygon></wp:wrapThrough>"#;

/// The baseline in device dots of the line "x" of [`blocked_by_a_wide_box`] with exact lines of
/// 18 pt beside a box of 72 pt with the wrap `wrap`, in steps, under `outline` and `end`.
fn stepped_baseline(wrap: &str, outline: PolygonWrap, end: StepEnd) -> i64 {
    let target = on_base_with(|p| {
        p.with_variant(BlockedLines::LineSteps)
            .with_variant(outline)
            .with_variant(end)
    });
    let body = blocked_by_a_wide_box(wrap, EXACT_18, 914_400);
    let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
    find(&pass.list, 'x').2
}

#[test]
fn moves_a_line_beside_a_polygon_outline_and_past_a_bottom_that_a_step_reaches() {
    // Steps of 18 pt from the box's top reach its bottom at 72 pt. Where a step on the bottom
    // still meets the wrap, the line takes one step more. Beside the outline, the line's band
    // from 36 to 54 pt lies beside the free left of the polygon's bottom half, 36 pt higher;
    // beside a rectangle the outline changes nothing.
    let at_bottom = stepped_baseline(THROUGH_OPEN_BOTTOM, PolygonWrap::Bounds, StepEnd::AtBottom);
    let cases = [
        (
            THROUGH_OPEN_BOTTOM,
            PolygonWrap::Bounds,
            StepEnd::PastBottom,
            360,
        ),
        (
            THROUGH_OPEN_BOTTOM,
            PolygonWrap::Outline,
            StepEnd::AtBottom,
            -720,
        ),
        (
            THROUGH_OPEN_BOTTOM,
            PolygonWrap::Outline,
            StepEnd::PastBottom,
            -720,
        ),
        (THROUGH, PolygonWrap::Outline, StepEnd::AtBottom, 0),
        (THROUGH, PolygonWrap::Outline, StepEnd::PastBottom, 360),
    ];
    let moves: Vec<i64> = cases
        .iter()
        .map(|&(wrap, outline, end, _)| stepped_baseline(wrap, outline, end) - at_bottom)
        .collect();
    let expected: Vec<i64> = cases.iter().map(|case| du(case.3)).collect();
    assert_eq!(moves, expected);
}

#[test]
fn moves_a_line_of_multiple_spacing_in_steps_of_its_single_line() {
    // Double lines of the fake font at 10 pt are 20 pt high, twice its single line of 10 pt.
    // Past a box of 24 pt, steps of the single line end at 30 pt, 6 pt below the box, where
    // steps of the line's height would end at 40 pt.
    const DOUBLE: &str = r#"<w:pPr><w:spacing w:line="480" w:lineRule="auto"/></w:pPr>"#;
    let case = (THROUGH, DOUBLE, 304_800);
    let (below, next) = blocked_baselines(case, BlockedLines::BelowBox);
    assert_eq!(next - below, du(400));
    let (x, _) = blocked_baselines(case, BlockedLines::LineSteps);
    assert_eq!(x - below, du(120));
}

/// A chart of columns without series, whose frame alone decides whether it is drawn.
fn chart_without_series() -> Chart {
    Chart {
        id: String::new(),
        columns: Some(Box::new(Columns::plain(
            Vec::new(),
            0,
            crate::chart::ChartGroup::Columns {
                gap: 150,
                overlap: 0,
                stacking: crate::chart::BarStacking::Clustered,
            },
            Some(Title {
                lines: 0,
                size: 28,
                font: crate::props::FontRef::MinorLatin,
                text: None,
                corner: None,
            }),
        ))),
    }
}

#[test]
fn leaves_out_a_drawing_beyond_the_range_of_a_length_with_a_warning() {
    // No file gives such a box, since every length that a reader takes lies within
    // `Length::FILE_LIMIT`: the test places the boxes past the largest length itself.
    let (styles, settings) = (Styles::default(), Settings::default());
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = base_context(&styles, &settings);
    let stories = context.for_stories();
    let sections = Sections::one(SectionLayout::plain(&Section::default(), 0));
    let mut layout = Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
    );
    let far = Length::from_units(i64::MAX);
    let page = (units(1_000), units(1_000));
    let shape = Floating {
        part: Name::new("word/header1.xml"),
        width: units(10),
        height: units(10),
        ..Floating::default()
    };
    let chart = Floating {
        chart: Some(chart_without_series()),
        ..shape.clone()
    };
    // The whole box, and the frame of a chart's columns.
    layout.show_floating((&shape, Size::of(&shape)), (far, Length::ZERO), page);
    let items = layout.draw_sized((&chart, Size::of(&chart)), Length::ZERO, far);
    assert_eq!(items.len(), 0);
    let skipped = |drawing| Warning::DrawingSkipped {
        drawing,
        part: Name::new("word/header1.xml"),
        reason: Reason::OutOfRange,
    };
    let warnings: Vec<(&Warning, u32)> = layout.output.warnings.iter().collect();
    assert_eq!(
        warnings,
        [(&skipped(Drawing::Shape), 1), (&skipped(Drawing::Chart), 1)]
    );
    assert_eq!((layout.items.len(), layout.behind.len()), (0, 0));
}

#[test]
fn leaves_out_a_chart_that_its_layout_gives_no_place_with_a_warning() {
    // A chart without series has no value axis, so the layout of its columns gives no place;
    // the reader never gives one, and the test makes it itself.
    let (styles, settings) = (Styles::default(), Settings::default());
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = base_context(&styles, &settings);
    let stories = context.for_stories();
    let sections = Sections::one(SectionLayout::plain(&Section::default(), 0));
    let mut layout = Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
    );
    let chart = Floating {
        part: Name::new("word/document.xml"),
        width: units(100),
        height: units(100),
        chart: Some(chart_without_series()),
        ..Floating::default()
    };
    layout.draw_sized((&chart, Size::of(&chart)), Length::ZERO, Length::ZERO);
    let warnings: Vec<(&Warning, u32)> = layout.output.warnings.iter().collect();
    let skipped = Warning::DrawingSkipped {
        drawing: Drawing::Chart,
        part: Name::new("word/document.xml"),
        reason: Reason::NotPlaced,
    };
    assert_eq!(warnings, [(&skipped, 1)]);
}

#[test]
fn places_a_drawing_from_the_top_of_its_anchors_line_on_a_target_that_counts_from_it() {
    use crate::layout::testing::{on_base_with, pass_with};
    use crate::numbering::Numbering;
    use crate::quirks::FromLine;
    use f_office_paint::{Item, PathCommand};
    let shape = AnchoredShape {
        across: ("margin", 0),
        down: ("line", 0),
        size: (254_000, 127_000),
        wrap: "<wp:wrapNone/>",
        outline: Some(12_700),
        text: None,
    }
    .drawing();
    // Lines of exactly 12 pt. The first drawing is anchored at the paragraph's start, the
    // second after a line break, on the second line.
    let body = format!(
        r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r>{shape}<w:t>A</w:t><w:br/><w:t>B</w:t></w:r><w:r>{shape}</w:r><w:r><w:t>C</w:t></w:r></w:p>"#
    );
    let tops = |from: FromLine| -> Vec<Length> {
        let target = on_base_with(|p| p.with_variant(from));
        let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
        let mut tops: Vec<Length> = list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Path(path) => path
                    .commands
                    .iter()
                    .flat_map(PathCommand::points)
                    .map(|point| point.y)
                    .min(),
                _ => None,
            })
            .collect();
        tops.sort();
        tops
    };
    let [first, second] = tops(FromLine::ParagraphTop).try_into().unwrap();
    assert_eq!(first, second);
    let line = Length::from_twips(240).unwrap();
    assert_eq!(tops(FromLine::LineTop), [first, first + line]);
}

/// The x in whole device dots of the first glyph of the line "a" of a text box placed `twips`
/// right of the page's left edge, with a black outline `outline` EMU wide, on a target whose
/// box outlines take `rule`.
fn box_line_x(twips: i64, outline: i64, rule: BoxOutlineLeft) -> i64 {
    let shape = AnchoredShape {
        across: ("page", twips * 635),
        down: ("paragraph", 0),
        size: (2_540_000, 508_000),
        wrap: "<wp:wrapNone/>",
        outline: Some(outline),
        text: Some(ShapeText {
            blocks: "<w:p><w:r><w:t>a</w:t></w:r></w:p>",
            body: r#"<wps:bodyPr lIns="91440" tIns="45720" rIns="91440" bIns="45720"/>"#,
        }),
    };
    let body = format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing());
    let target = on_base_with(|p| p.with_variant(rule));
    let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
    x_du(find(&list, 'a').1)
}

#[test]
fn cuts_half_a_text_box_outline_to_whole_twips_at_its_left_text_edge() {
    let shifts = |outline: i64| -> Vec<i64> {
        (2_000..2_012)
            .map(|twips| {
                box_line_x(twips, outline, BoxOutlineLeft::ExactHalf)
                    - box_line_x(twips, outline, BoxOutlineLeft::WholeTwipsHalf)
            })
            .collect()
    };
    // An outline of 15 twips keeps the text 7 twips in, not 7.5: some starts move a dot left.
    let start = shifts(9_525);
    assert!(
        start.iter().all(|shift| (0..=1).contains(shift)),
        "{start:?}"
    );
    assert!(start.contains(&1), "{start:?}");
    // An outline of 20 twips has a half of whole twips.
    assert!(shifts(12_700).iter().all(|&shift| shift == 0));
}

/// The x and the baseline in whole device dots of the first glyph of the line "a" of a VML text box placed
/// `twips` right of the page's left edge, with an outline of `line` (such as `strokeweight =
/// "0.75pt"`), on a target whose VML box outlines take `rule`.
fn vml_box_line(twips: i64, line: &str, rule: VmlBoxOutline) -> (i64, i64) {
    let body = format!(
        r##"<w:p><w:r><w:pict><v:shape xmlns:v="urn:schemas-microsoft-com:vml" type="#_x0000_t202" style="position:absolute;margin-left:{}.{:02}pt;margin-top:100pt;width:200pt;height:40pt;mso-position-horizontal-relative:page;mso-position-vertical-relative:page" {line}><v:textbox><w:txbxContent><w:p><w:r><w:t>a</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p>"##,
        twips / 20,
        twips % 20 * 5
    );
    let target = on_base_with(|p| p.with_variant(rule));
    let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
    let (_, x, baseline) = find(&list, 'a');
    (x_du(x), baseline)
}

#[test]
fn keeps_the_text_of_a_vml_box_inside_its_outline_by_its_half_rounded_up_to_whole_twips() {
    let shifts = |line: &str| -> Vec<(i64, i64)> {
        (2_000..2_012)
            .map(|twips| {
                let (inside, middle) = (
                    vml_box_line(twips, line, VmlBoxOutline::InsideRoundedHalf),
                    vml_box_line(twips, line, VmlBoxOutline::Middle),
                );
                (inside.0 - middle.0, inside.1 - middle.1)
            })
            .collect()
    };
    // An outline of 15 twips keeps the text 8 twips in, 1.67 dots of 4.8 twips: the starts
    // move one dot or two, and the baseline two.
    let thin = shifts(r#"strokeweight="0.75pt""#);
    assert!(thin.iter().all(|&(x, _)| (1..=2).contains(&x)), "{thin:?}");
    assert!(thin.iter().any(|&(x, _)| x == 1), "{thin:?}");
    assert!(thin.iter().any(|&(x, _)| x == 2), "{thin:?}");
    assert!(thin.iter().all(|&(_, y)| y == 2), "{thin:?}");
    // A box without an outline keeps its text where it was.
    assert!(
        shifts(r#"stroked="f""#)
            .iter()
            .all(|&shift| shift == (0, 0))
    );
}

/// The start and baseline, in dots, of the line of a VML shape of 400 by 100 pt with the
/// default insets, of the shape type `shape_type` (with the `id` `t`), against those of a text
/// box of its size.
fn vml_type_shift(shape_type: &str, attributes: &str) -> (i64, i64) {
    let line = |kind: &str, attributes: &str| {
        let body = format!(
            r##"<w:p><w:r><w:pict><v:shapetype xmlns:v="urn:schemas-microsoft-com:vml" {shape_type}><v:shape xmlns:v="urn:schemas-microsoft-com:vml" type="#{kind}" {attributes} style="position:absolute;margin-left:100pt;margin-top:100pt;width:400pt;height:100pt;mso-position-horizontal-relative:page;mso-position-vertical-relative:page" stroked="f"><v:textbox><w:txbxContent><w:p><w:r><w:t>a</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r></w:p>"##
        );
        let list = pass_with(&body, ("", None), None, Numbering::default(), on_base()).list;
        let (_, x, baseline) = find(&list, 'a');
        (x_du(x), baseline)
    };
    let (typed, plain) = (line("t", attributes), line("_x0000_t202", ""));
    (typed.0 - plain.0, typed.1 - plain.1)
}

#[test]
fn lays_the_text_of_a_vml_shape_in_its_types_text_rectangle_on_the_box_less_its_insets() {
    // A tenth of the 385.6 pt inside the insets across is 38.56 pt, 160.7 dots of 4.8 twips;
    // a twentieth of the 92.8 pt down is 4.64 pt, 19.3 dots.
    let (x, y) = vml_type_shift(
        r#"id="t" coordsize="21600,21600"><v:path textboxrect="2160,1080,19440,20520"/></v:shapetype"#,
        "",
    );
    assert!((160..=161).contains(&x), "{x}");
    assert!((19..=20).contains(&y), "{y}");
    // With a stretch point, the rectangle's 791 coordinates across scale as those down do:
    // 3.4 pt, 14.2 dots, each way. The shape's `adj` takes the place of the type's.
    let rounded = r#"id="t" coordsize="21600,21600" adj="5400"><v:formulas><v:f eqn="val #0"/><v:f eqn="prod @0 2929 10000"/><v:f eqn="sum width 0 @1"/><v:f eqn="sum height 0 @1"/></v:formulas><v:path limo="10800,10800" textboxrect="@1,@1,@2,@3"/></v:shapetype"#;
    let (x, y) = vml_type_shift(rounded, r#"adj="2700""#);
    assert!((14..=15).contains(&x), "{x}");
    assert!((14..=15).contains(&y), "{y}");
    // A formula that F-Office does not evaluate leaves the whole box.
    let unread = r#"id="t"><v:formulas><v:f eqn="sin #0 #1"/></v:formulas><v:path textboxrect="@0,0,21600,21600"/></v:shapetype"#;
    assert_eq!(vml_type_shift(unread, ""), (0, 0));
}

#[test]
fn places_a_header_drawing_from_the_body_area_on_a_target_that_asks() {
    use crate::layout::testing::{base, shape_top};
    use crate::quirks::StoryMarginArea;
    // A shape of the header at the top of the margins, above four lines with space after that
    // take the body down past the 1440 twip top margin: a target that keeps the section's
    // margins puts the shape at the top margin, one that takes the body's area at the body's
    // top. Without the four lines the header ends above the top margin and both agree.
    let shape = AnchoredShape {
        across: ("margin", 0),
        down: ("margin", 0),
        size: (914_400, 254_000),
        wrap: "<wp:wrapNone/>",
        outline: Some(12_700),
        text: None,
    };
    let lines = r#"<w:p><w:pPr><w:spacing w:after="400"/></w:pPr><w:r><w:t>h</w:t><w:br/><w:t>i</w:t><w:br/><w:t>j</w:t><w:br/><w:t>k</w:t></w:r></w:p>"#;
    let drawing = format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing());
    let lay_out = |area: StoryMarginArea, header: &str| {
        let target = on_base_with(|p| p.with_variant(area));
        pass_with(
            &p("b"),
            (NORMAL, None),
            Some(header),
            Numbering::default(),
            target,
        )
        .list
    };
    // The header ends at 720 + 200 + 4 x 200 + 400 = 2120 twips, where the body starts.
    let tall = format!("{drawing}{lines}");
    let section = lay_out(StoryMarginArea::SectionMargins, &tall);
    assert_eq!(find(&section, 'b').2, base(2120));
    let at_margin = shape_top(&lay_out(StoryMarginArea::SectionMargins, &drawing));
    assert_eq!(
        shape_top(&lay_out(StoryMarginArea::BodyArea, &drawing)),
        at_margin
    );
    assert_eq!(shape_top(&section), at_margin);
    assert_eq!(
        shape_top(&lay_out(StoryMarginArea::BodyArea, &tall)),
        at_margin + (2120 - 1440) * Length::UNITS_PER_TWIP
    );
}

/// The top of a text box in units and the baseline in device dots of its line "a": the box
/// lies `down` (what the place down counts from, and the offset in whole twips) below
/// `before` paragraphs of the line "b" spaced 250/240 of a single line, with a black outline
/// `outline` EMU wide, on a target whose box text tops take `rule`.
fn box_top_and_line(
    down: (&str, i64),
    before: usize,
    outline: i64,
    rule: BoxTextTop,
) -> (i64, i64) {
    let shape = AnchoredShape {
        across: ("page", 2_000 * 635),
        down: (down.0, down.1 * 635),
        size: (2_540_000, 508_000),
        wrap: "<wp:wrapNone/>",
        outline: Some(outline),
        text: Some(ShapeText {
            blocks: "<w:p><w:r><w:t>a</w:t></w:r></w:p>",
            body: r#"<wps:bodyPr lIns="91440" tIns="45720" rIns="91440" bIns="45720"/>"#,
        }),
    };
    let spaced = r#"<w:p><w:pPr><w:spacing w:line="250" w:lineRule="auto"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let body = format!(
        "{}<w:p><w:r>{}</w:r></w:p>",
        spaced.repeat(before),
        shape.drawing()
    );
    let target = on_base_with(|p| p.with_variant(rule));
    let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
    (shape_top(&list), find(&list, 'a').2)
}

#[test]
fn starts_a_text_box_text_from_its_top_rounded_to_whole_twips() {
    use BoxTextTop::{ExactTop, NearestTwipTop};
    let twip = Length::UNITS_PER_TWIP;
    let mut moved = 0;
    for (before, offset) in (0..6).flat_map(|before| (100..112).map(move |offset| (before, offset)))
    {
        // The paragraphs above put the box's top at thirds of a twip. Its outline of 20 twips
        // has a half of whole twips, and the drawn outline starts that half above the box.
        let (top, rounded) =
            box_top_and_line(("paragraph", offset), before, 12_700, NearestTwipTop);
        let nearest = (top + 10 * twip + twip / 2).div_euclid(twip);
        // The text starts as in a box placed from the page at the nearest whole twip.
        let placed = box_top_and_line(("page", nearest), 0, 12_700, ExactTop).1;
        assert_eq!(rounded, placed, "{before} {offset}");
        let exact = box_top_and_line(("paragraph", offset), before, 12_700, ExactTop).1;
        moved += i64::from(rounded != exact);
    }
    assert!(moved > 0);
    // An outline of 15 twips keeps the text 7 twips below the box's top, as one of 14 twips
    // does, and some lines move a dot up.
    let mut cut = 0;
    for twips in 2_000..2_024 {
        let line = |outline, rule| box_top_and_line(("page", twips), 0, outline, rule).1;
        assert_eq!(
            line(9_525, NearestTwipTop),
            line(8_890, ExactTop),
            "{twips}"
        );
        cut += i64::from(line(9_525, NearestTwipTop) != line(9_525, ExactTop));
    }
    assert!(cut > 0);
}

/// The lines of the box of [`last_line`], of 12.5 pt unless one says another size.
#[derive(Clone, Copy, Debug)]
enum BoxLines {
    /// One line of single spacing without space before or after.
    Single,
    /// One line of single spacing without space before or after, of 10 pt: on the base target's
    /// dots of 0.24 pt a height of 41.67 dots, which rounds up, and an ascent and a descent
    /// that round to one dot less.
    SingleRoundsUp,
    /// One line of single spacing with space after.
    SpacedAfter,
    /// A line of 1.15 times single spacing above a line of single spacing.
    MultipleAbove,
}

/// Where a text box whose height runs `twips` past 400 twips puts the baseline of its last line,
/// the letter `a`, under `rule`, in dots.
fn last_line(twips: i64, lines: BoxLines, rule: BoxLastLine) -> i64 {
    let sized = |size: i64, line: i64, after: i64, letter: char| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="{after}" w:line="{line}" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="{size}"/></w:rPr><w:t>{letter}</w:t></w:r></w:p>"#
        )
    };
    let paragraph = |line: i64, after: i64, letter: char| sized(25, line, after, letter);
    let blocks = match lines {
        BoxLines::Single => paragraph(240, 0, 'a'),
        BoxLines::SingleRoundsUp => sized(20, 240, 0, 'a'),
        BoxLines::SpacedAfter => paragraph(240, 120, 'a'),
        BoxLines::MultipleAbove => paragraph(276, 0, 'b') + &paragraph(240, 0, 'a'),
    };
    let shape = AnchoredShape {
        across: ("page", 2_000 * 635),
        down: ("page", 2_000 * 635),
        size: (2_540_000, (400 + twips) * 635),
        wrap: "<wp:wrapNone/>",
        outline: None,
        text: Some(ShapeText {
            blocks: &blocks,
            body: r#"<wps:bodyPr lIns="91440" tIns="45720" rIns="91440" bIns="45720" anchor="t"><a:noAutofit/></wps:bodyPr>"#,
        }),
    };
    let body = format!("<w:p><w:r>{}</w:r></w:p>", shape.drawing());
    let target = on_base_with(|p| p.with_variant(rule));
    let list = pass_with(&body, ("", None), None, Numbering::default(), target).list;
    find(&list, 'a').2
}

#[test]
fn moves_a_text_box_last_line_down_by_the_room_below_it() {
    use BoxLastLine::{RoomBelow, Spaced};
    // Each twip of height moves the room below the line by a part of a dot: the line sits one
    // dot lower in some boxes and keeps its place in the others.
    let moves: Vec<i64> = (0..24)
        .map(|twips| {
            last_line(twips, BoxLines::Single, RoomBelow)
                - last_line(twips, BoxLines::Single, Spaced)
        })
        .collect();
    let lower = moves.iter().filter(|&&dots| dots == 1).count();
    assert!((1..24).contains(&lower), "{moves:?}");
    assert!(
        moves.iter().all(|&dots| dots == 0 || dots == 1),
        "{moves:?}"
    );
    // A line whose height rounds up, which its spacing puts from its rounded exact bottom, sits
    // from its rounded top too: one dot off its spacing's place where its top's part of a dot
    // and the room below it put it there, and at its spacing's place in the others.
    let moves: Vec<i64> = (0..24)
        .map(|twips| {
            last_line(twips, BoxLines::SingleRoundsUp, RoomBelow)
                - last_line(twips, BoxLines::SingleRoundsUp, Spaced)
        })
        .collect();
    let off_spacing = moves.iter().filter(|&&dots| dots != 0).count();
    assert!((1..24).contains(&off_spacing), "{moves:?}");
    assert!(moves.iter().all(|&dots| dots.abs() <= 1), "{moves:?}");
    // A line with space after, and a line below a line of other spacing, keep the place of
    // their spacing.
    for lines in [BoxLines::SpacedAfter, BoxLines::MultipleAbove] {
        for twips in 0..24 {
            assert_eq!(
                last_line(twips, lines, RoomBelow),
                last_line(twips, lines, Spaced),
                "{lines:?} {twips}"
            );
        }
    }
}

/// A through wrap whose outline's top slants from 15 pt down the box at its left to 12 pt at its
/// right, on a box 72 pt high.
const THROUGH_SLANTED_TOP: &str = r#"<wp:wrapThrough wrapText="bothSides"><wp:wrapPolygon edited="1"><wp:start x="0" y="4500"/><wp:lineTo x="0" y="21600"/><wp:lineTo x="21600" y="21600"/><wp:lineTo x="21600" y="3600"/><wp:lineTo x="0" y="4500"/></wp:wrapPolygon></wp:wrapThrough>"#;

/// The baseline in device dots of the line "x", in the fake font at 10 pt with the paragraph
/// properties `spacing`, that anchors a box as wide as the page and 1 inch high with the wrap
/// `wrap` at the paragraph's top, under `band`, where a line meets a polygon's outline.
fn wrap_band_baseline(wrap: &str, spacing: &str, band: LineWrapBand) -> i64 {
    let target = on_base_with(|p| p.with_variant(PolygonWrap::Outline).with_variant(band));
    let shape = AnchoredShape {
        across: ("page", 0),
        down: ("paragraph", 0),
        size: (7_772_400, 914_400),
        wrap,
        outline: None,
        text: None,
    };
    let body = format!(
        "<w:p>{spacing}<w:r>{}</w:r><w:r><w:t>x</w:t></w:r></w:p>",
        shape.drawing()
    );
    let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
    find(&pass.list, 'x').2
}

#[test]
fn a_line_of_multiple_spacing_meets_an_outline_over_its_single_line() {
    // A line of double spacing is 20 pt high over a single line of 10 pt. The outline's top,
    // 12 to 15 pt down across the page, lies in its extra: the whole line meets the outline
    // and goes below the box, 72 pt down, and its single line does not. An exact line of 20 pt
    // meets the outline under both.
    const DOUBLE: &str = r#"<w:pPr><w:spacing w:line="480" w:lineRule="auto"/></w:pPr>"#;
    const EXACT_20: &str = r#"<w:pPr><w:spacing w:line="400" w:lineRule="exact"/></w:pPr>"#;
    let moves = |wrap, spacing| {
        wrap_band_baseline(wrap, spacing, LineWrapBand::WholeLine)
            - wrap_band_baseline(wrap, spacing, LineWrapBand::SingleLine)
    };
    assert_eq!(
        [
            moves(THROUGH_SLANTED_TOP, DOUBLE),
            moves(THROUGH_SLANTED_TOP, EXACT_20),
        ],
        [du(1440), 0]
    );
}