f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! The lines of paragraphs: strike lines, underlines, revision bars, line heights, the line
//! grid and the spaces and room of East Asian text.

use f_office_paint::Item;
use f_office_units::Length;

use crate::grid::DOT;
use crate::layout::testing::{
    EAST_ASIAN_FAKE, NORMAL, at, base, du, find, lay_out, on_base_with, p, pass_with, rects, table,
};
use crate::numbering::Numbering;
use crate::quirks::{GridSingleLine, NoBreakSpaceShare};

#[test]
fn draws_a_line_through_struck_text_at_the_strikeout_position() {
    let list = lay_out(
        "<w:p><w:r><w:rPr><w:strike/></w:rPr><w:t>a</w:t></w:r></w:p>",
        NORMAL,
        None,
    );
    let baseline = find(&list, 'a').2 * DOT;
    let lines: Vec<(i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some((r.y.units(), r.height.units())),
            _ => None,
        })
        .collect();
    // At 10 pt, the strikeout's top is 250 units of the 1000 unit em above the baseline, 2.5 pt
    // or 10.42 device dots, and the line is 50 units thick, 0.5 pt or 2.08 device dots. Both
    // round to whole device dots.
    assert_eq!(lines, vec![(baseline - 10 * DOT, 2 * DOT)]);
}

#[test]
fn underlines_an_underlined_tab_across_its_space() {
    let list = lay_out(
        r#"<w:p><w:pPr><w:tabs><w:tab w:val="left" w:pos="2880"/></w:tabs></w:pPr><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>a</w:t><w:tab/></w:r></w:p>"#,
        NORMAL,
        None,
    );
    let (_, x, _) = find(&list, 'a');
    let mut spans: Vec<(i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some((r.x.units(), r.x.units() + r.width.units())),
            _ => None,
        })
        .collect();
    spans.sort_unstable();
    // The glyph's underline ends where the tab starts, 5 pt later, and the tab's underline
    // runs on to the stop at 2 inches from the margin, each end on its nearest device dot.
    let glyph = f_office_units::div_round(x + 100 * Length::UNITS_PER_TWIP, DOT) * DOT;
    let stop = 1440 * Length::UNITS_PER_TWIP + 2880 * Length::UNITS_PER_TWIP;
    assert_eq!(spans, vec![(x, glyph), (glyph, stop)]);
}

#[test]
fn marks_a_line_with_a_tracked_change_in_the_margin() {
    let changed = lay_out(
        r#"<w:p><w:r><w:t>a</w:t></w:r><w:ins w:author="A"><w:r><w:t>b</w:t></w:r></w:ins></w:p><w:p><w:r><w:t>c</w:t></w:r></w:p>"#,
        NORMAL,
        None,
    );
    // The 72 pt margin puts the bar at 36 pt, three device dots wide, from the top of the
    // changed line. The line after it has no change and no bar.
    let bars: Vec<_> = rects(&changed, 0)
        .into_iter()
        .filter(|r| r.0 == 150 && r.2 == 3)
        .collect();
    assert_eq!(bars.len(), 1);
    assert_eq!(bars[0].1, 300);
    let plain = lay_out(&p("a"), NORMAL, None);
    assert!(rects(&plain, 0).iter().all(|r| r.0 != 150));
}

#[test]
fn marks_the_line_of_a_changed_or_inserted_paragraph_mark() {
    let bars = |mark: &str| {
        let body = format!("{}<w:p><w:pPr><w:rPr>{mark}</w:rPr></w:pPr></w:p>", p("a"));
        let list = lay_out(&body, NORMAL, None);
        rects(&list, 0)
            .into_iter()
            .filter(|r| r.0 == 150 && r.2 == 3)
            .map(|r| r.1)
            .collect::<Vec<_>>()
    };
    // The empty second paragraph's line starts at 1640 twips, 341.67 device dots, which the
    // rectangles of the test round down.
    let second = 1640 * Length::UNITS_PER_TWIP / DOT;
    // A formatting change of the mark and an inserted mark mark its line.
    assert_eq!(
        bars(r#"<w:rPrChange w:author="A"><w:rPr><w:b/></w:rPr></w:rPrChange>"#),
        [second]
    );
    assert_eq!(bars(r#"<w:ins w:author="A"/>"#), [second]);
    // A deleted mark, and a mark without a change, do not.
    assert_eq!(bars(r#"<w:del w:author="A"/>"#), [] as [i64; 0]);
    assert_eq!(bars("<w:b/>"), [] as [i64; 0]);
}

#[test]
fn puts_the_underline_on_whole_device_dots() {
    let list = lay_out(
        r#"<w:p><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>a</w:t></w:r></w:p>"#,
        NORMAL,
        None,
    );
    let line = list.pages()[0].items().iter().find_map(|item| match item {
        Item::Rect(rect) => Some((rect.y.units(), rect.height.units())),
        _ => None,
    });
    // The fake font puts the underline 1 pt (4.17 device dots) below the baseline and makes
    // it 0.5 pt (2.08 device dots) thick at 10 pt. Both round to whole device dots.
    let baseline = base(1440) * DOT;
    assert_eq!(line, Some((baseline + 4 * DOT, 2 * DOT)));
}

/// Styles whose run defaults have the run properties `fonts`.
fn run_defaults(fonts: &str) -> String {
    format!(
        r"<w:docDefaults><w:rPrDefault><w:rPr>{fonts}</w:rPr></w:rPrDefault><w:pPrDefault/></w:docDefaults>{NORMAL}"
    )
}

/// The places of `中1a文` between its four characters, in units, laid out with `styles`.
fn east_asian_gaps(body: &str, styles: &str) -> [i64; 3] {
    let list = lay_out(body, styles, None);
    let x = |ch: char| find(&list, ch).1;
    [x('1') - x('中'), x('a') - x('1'), x('文') - x('a')]
}

#[test]
fn spaces_east_asian_letters_from_digits_and_latin_letters() {
    // Glyphs of the fake font are 5 pt wide at 10 pt. A quarter em, 2.5 pt, goes between an
    // ideograph and a digit or a Latin letter, on either side, and not between a digit and a
    // letter, when the run defaults name a font made for East Asian text in their East Asian
    // slot.
    let pt = |v: i64| v * 25_400 / 2;
    let styles = run_defaults(&format!(r#"<w:rFonts w:eastAsia="{EAST_ASIAN_FAKE}"/>"#));
    assert_eq!(
        east_asian_gaps(&p("中1a文"), &styles),
        [pt(15), pt(10), pt(15)]
    );
    // A paragraph can turn either space off.
    let off = r#"<w:p><w:pPr><w:autoSpaceDN w:val="0"/></w:pPr><w:r><w:t>中1a文</w:t></w:r></w:p>"#;
    assert_eq!(east_asian_gaps(off, &styles), [pt(10), pt(10), pt(15)]);
    // A theme font counts even where the theme has no face for it.
    let themed = run_defaults(r#"<w:rFonts w:eastAsiaTheme="minorEastAsia"/>"#);
    assert_eq!(
        east_asian_gaps(&p("中1a文"), &themed),
        [pt(15), pt(10), pt(15)]
    );
}

#[test]
fn gives_no_east_asian_space_without_an_east_asian_default_font() {
    // Without an East Asian font in the run defaults, or with a Latin one, there is no space,
    // even for text whose style names an East Asian face and language.
    let pt = |v: i64| v * 25_400 / 2;
    let language = format!(
        r#"{NORMAL}<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:rFonts w:eastAsia="{EAST_ASIAN_FAKE}"/><w:lang w:eastAsia="zh-CN"/></w:rPr></w:style>"#
    );
    let latin = run_defaults(r#"<w:rFonts w:eastAsia="Fake Sans"/>"#);
    for styles in [language.as_str(), NORMAL, &latin] {
        assert_eq!(east_asian_gaps(&p("中1a文"), styles), [pt(10); 3]);
    }
}

/// How far `b` lies from `a` in a filled justified line that starts with `a`, a no-break space
/// and `b`, laid out with `styles` in compatibility `mode` on the base target with the variant
/// `share`.
fn no_break_gap(styles: &str, mode: u32, share: NoBreakSpaceShare) -> i64 {
    no_break_gap_after(r#"<w:r><w:t xml:space="preserve">a"#, styles, mode, share)
}

/// [`no_break_gap`] where `start` opens the run of the no-break space, after the runs before it.
fn no_break_gap_after(start: &str, styles: &str, mode: u32, share: NoBreakSpaceShare) -> i64 {
    let text = format!("\u{a0}b {}", "c ".repeat(80));
    let body =
        format!(r#"<w:p><w:pPr><w:jc w:val="both"/></w:pPr>{start}{text}</w:t></w:r></w:p>"#);
    let target = on_base_with(|profile| profile.with_variant(share));
    let list = pass_with(
        &body,
        (styles, Some(mode)),
        None,
        Numbering::default(),
        target,
    )
    .list;
    find(&list, 'b').1 - find(&list, 'a').1
}

#[test]
fn stretches_a_no_break_space_below_mode_15_with_east_asian_run_defaults() {
    use NoBreakSpaceShare::{EastAsianDefaults, None as Kept};
    let east_asian = run_defaults(&format!(r#"<w:rFonts w:eastAsia="{EAST_ASIAN_FAKE}"/>"#));
    let latin = run_defaults(r#"<w:rFonts w:eastAsia="Fake Sans"/>"#);
    let template = format!("<w:docDefaults><w:pPrDefault/></w:docDefaults>{NORMAL}");
    for styles in [east_asian.as_str(), &template] {
        let kept = no_break_gap(styles, 12, Kept);
        assert!(no_break_gap(styles, 12, EastAsianDefaults) > kept);
        assert!(no_break_gap(styles, 14, EastAsianDefaults) > kept);
        // From mode 15 the no-break space keeps its width.
        assert_eq!(
            no_break_gap(styles, 15, EastAsianDefaults),
            no_break_gap(styles, 15, Kept)
        );
    }
    // A Latin face in the East Asian slot, and run defaults without one, keep its width too.
    for styles in [latin.as_str(), NORMAL] {
        assert_eq!(
            no_break_gap(styles, 12, EastAsianDefaults),
            no_break_gap(styles, 12, Kept)
        );
    }
}

#[test]
fn keeps_the_width_of_a_no_break_space_that_starts_a_text_object() {
    use NoBreakSpaceShare::{EastAsianDefaults, None as Kept};
    let template = format!("<w:docDefaults><w:pPrDefault/></w:docDefaults>{NORMAL}");
    let gap = |start: &str, share| no_break_gap_after(start, &template, 12, share);
    let kept = gap(r#"<w:r><w:t xml:space="preserve">a"#, Kept);
    // A run with another revision ID starts a text object at the no-break space.
    let apart = r#"<w:r><w:t>a</w:t></w:r><w:r w:rsidR="00100001"><w:t xml:space="preserve">"#;
    assert_eq!(gap(apart, EastAsianDefaults), kept);
    // A run written as the one before continues its text object.
    let alike = r#"<w:r><w:t>a</w:t></w:r><w:r><w:t xml:space="preserve">"#;
    assert!(gap(alike, EastAsianDefaults) > kept);
}

#[test]
fn puts_a_multiple_of_single_spacing_in_that_many_steps_of_a_line_grid() {
    // Double spacing on a grid of 18 pt fills two steps, 36 pt, where the fake font's single
    // line of 10 pt needs one. The single line lies in its middle: 13 pt below the top, and
    // the ascent of 8 pt (33.33 device dots, rounded to 33) below that.
    let grid = r#"<w:sectPr><w:docGrid w:type="lines" w:linePitch="360"/></w:sectPr>"#;
    let double = |text: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:line="480" w:lineRule="auto"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let list = lay_out(&(double("a") + &double("b") + grid), NORMAL, None);
    let (_, ya) = at(&list, 'a');
    let (_, yb) = at(&list, 'b');
    assert_eq!(yb - ya, du(720));
    assert_eq!(ya, du(1440 + 260) + 33);
    // A multiple of 1.5 fills one and a half steps, 27 pt.
    let half = |text: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:line="360" w:lineRule="auto"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let list = lay_out(&(half("a") + &half("b") + grid), NORMAL, None);
    assert_eq!(at(&list, 'b').1 - at(&list, 'a').1, du(540));
    // In table cells, without `w:adjustLineHeightInTable`, the lines keep their own height:
    // the doubled line of 20 pt.
    let cells = table(
        "",
        &[4000],
        &[("", &[double("a").as_str()]), ("", &[double("b").as_str()])],
    );
    let list = lay_out(&(cells + "<w:p/>" + grid), NORMAL, None);
    assert_eq!(at(&list, 'b').1 - at(&list, 'a').1, du(400));
}

#[test]
fn places_a_single_line_in_its_grid_steps_from_the_parts_that_the_target_rounds() {
    // Single lines of the fake font on a grid, the first line's top at 300 device dots. In the
    // middle of the steps, the baseline lies the single line less its rounded descent plus
    // half of what the steps add; with the parts and the steps' height each rounded, the
    // rounded ascent plus half of what the rounded height adds, a half down the page, below
    // the top's dot.
    // - 11 pt on 18 pt (75 dots), the ascent 36.67 dots and the descent 9.17: in the middle,
    //   45.83 - 9 + (75 - 45.83) / 2 = 51.42, 351; rounded, 37 + (75 - 46) / 2 = 51.5, 352.
    // - 10 pt on 305 twips (63.54 dots), the ascent 33.33 and the descent 8.33: in the
    //   middle, 41.67 - 8 + (63.54 - 41.67) / 2 = 44.6, 345, and from the second top at
    //   363.54, 408; rounded, 33 + (64 - 41) / 2 = 44.5, 45: 345, and 364 + 45 = 409.
    // - 10 pt on 300 twips (62.5 dots), 15 pt, which binary points hold: in the middle, 44.08
    //   below the tops, 344 and 407; rounded, the steps' height of 62.5 goes down the page to
    //   63, 33 + (63 - 41) / 2 = 44 below the tops, and the second top at 362.5 goes down the
    //   page to 363: 344 and 407.
    // - 10 pt on 276 twips (57.5 dots), 13.8 pt, which binary points do not hold: in the
    //   middle, 41.67 - 8 + (57.5 - 41.67) / 2 = 41.58, 342 and 399; rounded, the height goes up
    //   the page to 57, 33 + (57 - 41) / 2 = 41, and the second top at 357.5 up the page to
    //   357: 341 and 398.
    let line = |text: &str, size: u32| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="auto" w:after="0"/></w:pPr><w:r><w:rPr><w:sz w:val="{size}"/></w:rPr><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    for (pitch, size, middle, rounded) in [
        (360, 22, (351, 426), (352, 427)),
        (305, 20, (345, 408), (345, 409)),
        (300, 20, (344, 407), (344, 407)),
        (276, 20, (342, 399), (341, 398)),
        // 11 pt on 220 twips (45.83 dots): the exact single line fits one step, though its
        // rounded parts (37 + 9 = 46 dots) pass it; rounded, 37 below the tops, 337 and 383.
        (220, 22, (337, 383), (337, 383)),
    ] {
        let grid =
            format!(r#"<w:sectPr><w:docGrid w:type="lines" w:linePitch="{pitch}"/></w:sectPr>"#);
        let body = line("a", size) + &line("b", size) + &grid;
        for (variant, (first, second)) in [
            (GridSingleLine::Middle, middle),
            (GridSingleLine::PartsRounded, rounded),
        ] {
            let target = on_base_with(|profile| profile.with_variant(variant));
            let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
            assert_eq!(at(&list, 'a').1, first, "{pitch} {variant:?}");
            assert_eq!(at(&list, 'b').1, second, "{pitch} {variant:?}");
        }
    }
}

#[test]
fn puts_the_baseline_of_an_at_least_line_up_from_its_rounded_bottom() {
    // Lines of the fake font at 10 pt with a minimum of 14.1 pt (282 twips), above their
    // single line of 10 pt. The first line's bottom at 1,722 twips (358.75 device dots)
    // rounds to 359, and the descent of 2 pt (8.33 units) to 8, so the baseline lies at 351
    // units, where the exact baseline at 1,682 twips would round to 350. The second line's
    // bottom at 2,004 twips (417.5 units) rounds to 418, so its baseline lies at 410.
    let line = |text: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:line="282" w:lineRule="atLeast" w:after="0"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let list = lay_out(&(line("a") + &line("b")), NORMAL, None);
    assert_eq!(at(&list, 'a').1, 351);
    assert_eq!(at(&list, 'b').1, 410);
}

#[test]
fn gives_lines_of_east_asian_fonts_room_above_and_below() {
    // The fake font's line is 1 em, 0.8 above the baseline. A font made for East Asian text
    // gets 0.15 of it more above and below, so 10 pt lines are 13 pt apart. The line of 54.17
    // device dots rounds down to 54, and the descent of 3.5 pt (70 twips, 14.58 units)
    // rounds to 15, so the first baseline is 39 units below the top, at 1,629 twips.
    let run = |text: &str| {
        format!(
            r#"<w:p><w:r><w:rPr><w:rFonts w:ascii="{EAST_ASIAN_FAKE}" w:hAnsi="{EAST_ASIAN_FAKE}"/></w:rPr><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let list = lay_out(&(run("a") + &run("b")), NORMAL, None);
    let (_, ya) = at(&list, 'a');
    let (_, yb) = at(&list, 'b');
    assert_eq!(yb - ya, du(260));
    assert_eq!(ya, du(1440) + 39);
}

#[test]
fn gives_no_east_asian_room_to_complex_script_text() {
    // A right-to-left run takes its complex script font, here the East Asian fake font, whose
    // line gets no room above and below for that text: its 10 pt lines lie as far apart as
    // those of the plain fake font.
    let pitch = |props: &str| {
        let run =
            |text: &str| format!(r"<w:p><w:r><w:rPr>{props}</w:rPr><w:t>{text}</w:t></w:r></w:p>");
        let list = lay_out(&(run("a") + &run("b")), NORMAL, None);
        at(&list, 'b').1 - at(&list, 'a').1
    };
    let complex = pitch(&format!(r#"<w:rFonts w:cs="{EAST_ASIAN_FAKE}"/><w:rtl/>"#));
    assert_eq!(complex, pitch(""));
    assert!(complex < du(260), "{complex}");
}

/// The fake fonts with an em of 2,048 units, a line of 2,500 and a descent of 550 on every
/// target, as a face of the size of em that a writer of whole 1/4096 pt holds.
struct Em2048;

impl crate::Fonts for Em2048 {
    fn face(
        &self,
        family: &f_office_fonts::FamilyName,
        bold: bool,
        italic: bool,
    ) -> Option<crate::ChosenFace> {
        let mut face = crate::layout::testing::Fake.face(family, bold, italic)?;
        face.metrics.units_per_em = 2048;
        face.metrics.hhea_ascender = 1950;
        face.metrics.hhea_descender = -550;
        face.metrics.line_top = 1950;
        face.metrics.script_top = 1950;
        face.metrics.descent = 550;
        Some(face)
    }

    fn glyph(&self, font: f_office_fonts::FontId, ch: char) -> Option<u32> {
        crate::layout::testing::Fake.glyph(font, ch)
    }

    fn advance(&self, font: f_office_fonts::FontId, glyph: u32) -> Option<u16> {
        crate::layout::testing::Fake.advance(font, glyph)
    }
}

#[test]
fn adds_the_heights_of_lines_of_faces_of_2048_units_per_em_in_the_targets_unit() {
    use crate::quirks::LineHeightUnit;
    // Forty one-line paragraphs at 10.5 pt with the spacing 276 240ths, from the top margin of
    // 1 inch, which lies on a whole dot of each target. The single line is 2,500 × 21 = 52,500
    // parts of 1/4096 pt, and the line 60,375 parts: 374,395.75 half-EMUs. F-Office's own
    // height takes 1.15 times its single line of 325,562, rounded: 374,396. On a dot of
    // 0.12 pt, 7 of the 40 lines lie on another dot.
    let paragraph = r#"<w:p><w:pPr><w:spacing w:after="0" w:line="276" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="21"/></w:rPr><w:t>q</w:t></w:r></w:p>"#;
    let body = paragraph.repeat(40);
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let top = 1440 * Length::UNITS_PER_TWIP;
    let mut seen = Vec::new();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let unit = profile.quirks().line_height_unit;
        let dot = profile.device_dot().units();
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Em2048, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let baselines: Vec<i64> = list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Glyphs(run) => run.glyphs.first().map(|g| g.y.units()),
                _ => None,
            })
            .collect();
        assert_eq!(baselines.len(), 40, "{target}");
        // Each line's top rounds to its dot, a half up, and the baseline lies the same whole
        // dots below it. The exact tops are in 1/512 half-EMU.
        let step = match unit {
            LineHeightUnit::Whole4096ths => 60_375 * 3_175,
            LineHeightUnit::HalfEmus => 374_396 * 512,
        };
        let dots = |k: i64| f_office_units::div_round(top * 512 + k * step, dot * 512);
        let expected: Vec<i64> = (0..40)
            .map(|k| baselines[0] + (dots(k) - dots(0)) * dot)
            .collect();
        assert_eq!(baselines, expected, "{target}");
        seen.push(unit);
    }
    assert!(seen.contains(&LineHeightUnit::Whole4096ths));
    assert!(seen.contains(&LineHeightUnit::HalfEmus));
}

#[test]
fn adds_a_list_labels_rise_in_whole_4096ths_where_the_target_holds_heights_in_them() {
    use crate::quirks::LineHeightUnit;
    use crate::testing::WordParts;
    // Forty list items of 11 pt text with the spacing 243 240ths, whose labels of 13 pt rise
    // above the text, from the top margin of 1 inch, which lies on a whole dot of each target.
    // The text's single line is 2,500 × 22 = 55,000 parts of 1/4096 pt, 55,687.5 at 243
    // 240ths, and the label rises (1,950 × 26) − (1,950 × 22) = 7,800 parts above the text. In
    // whole parts the line is 55,688 + 7,800 = 63,488 parts high: half a part more than its
    // exact height, which a height in half-EMUs keeps within 2 half-EMUs. The line's top lies
    // close to half a dot of 0.12 pt every other line, so the half part puts some lines on
    // another dot.
    let numbering = r#"<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="q"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:rPr><w:sz w:val="26"/></w:rPr></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>"#;
    let paragraph = r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr><w:spacing w:after="0" w:line="243" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>q</w:t></w:r></w:p>"#;
    let page = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/></w:sectPr>"#;
    let bytes = crate::testing::docx(&format!("{}{page}", paragraph.repeat(40)))
        .word_part("n1", "numbering", "numbering.xml", "numbering", numbering)
        .zip()
        .unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let top = 1440 * Length::UNITS_PER_TWIP;
    // The exact tops are in 1/512 half-EMU: 3,175 of them make a part of 1/4096 pt.
    let whole = 63_488 * 3_175;
    let exact = 126_975 * 3_175 / 2;
    let mut seen = Vec::new();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let unit = profile.quirks().line_height_unit;
        seen.push(unit);
        if unit != LineHeightUnit::Whole4096ths {
            continue;
        }
        let dot = profile.device_dot().units();
        let dots = |k: i64, step: i64| f_office_units::div_round(top * 512 + k * step, dot * 512);
        let mut baselines = first_page_baselines(&package, target);
        // The label and the text of a line stand on one baseline.
        baselines.dedup();
        assert_eq!(baselines.len(), 40, "{target}");
        let expected: Vec<i64> = (0..40)
            .map(|k| baselines[0] + (dots(k, whole) - dots(0, whole)) * dot)
            .collect();
        assert_eq!(baselines, expected, "{target}");
        // A height within 2 half-EMUs of the exact one puts some line on another dot.
        let off = (0..40).filter(|&k| {
            let near = [exact - 1024, exact + 1024].map(|step| dots(k, step));
            near.iter().all(|&d| d != dots(k, whole))
        });
        assert!(off.count() > 0, "{target}");
    }
    assert!(seen.contains(&LineHeightUnit::Whole4096ths));
}

/// The baseline of the first glyph of each glyph run on the first page of `package`, laid out
/// for `target` with the faces of 2,048 units per em.
fn first_page_baselines(package: &f_office_opc::Package, target: crate::Target) -> Vec<i64> {
    page_baselines(package, target, 0)
}

/// The baseline of the first glyph of each glyph run on the page `page` of `package`, laid out
/// for `target` with the faces of 2,048 units per em.
fn page_baselines(package: &f_office_opc::Package, target: crate::Target, page: usize) -> Vec<i64> {
    let options = crate::Options {
        configuration: crate::Configuration::of(target),
        ..crate::Options::default()
    };
    let list = crate::layout(package, (&Em2048, &crate::ArtPictures::new()), &options)
        .unwrap()
        .value;
    list.pages()[page]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => run.glyphs.first().map(|g| g.y.units()),
            _ => None,
        })
        .collect()
}

#[test]
fn adds_lengths_of_whole_twips_down_the_page_in_the_targets_unit() {
    use crate::quirks::{ExactSpacedBottom, TwipLengthUnit};
    // Forty one-line paragraphs at 1 pt from the top margin of 1 inch, which lies on a whole
    // dot of each target, in three cases: exact lines of 43 twips; exact lines of 40 twips with
    // 43 twips of space after; and at-least lines whose minimum of 43 twips sets their height.
    // 43 twips are 8,806.4 parts of 1/4096 pt, so in whole parts each enters 0.4 part short,
    // and 40 twips are 8,192 parts exactly. Each line's baseline rounds from its exact bottom,
    // or from its exact top where a spaced exact line rounds its top and height on their own,
    // which lies exactly half a dot past a whole dot every 12 paragraphs: in half-EMUs it takes
    // the lower dot, and with the parts that each length lost it takes the higher one.
    let cases = [("exact", 43, 0), ("exact", 40, 43), ("atLeast", 43, 0)];
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let top = 1440 * Length::UNITS_PER_TWIP;
    let rest_parts = 512;
    let rest_per_part = 3_175;
    let parts = |twips: i64| f_office_units::div_round(twips * 4_096, 20);
    let mut seen = Vec::new();
    for (rule, line, after) in cases {
        let paragraph = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="{after}" w:line="{line}" w:lineRule="{rule}"/></w:pPr><w:r><w:rPr><w:sz w:val="2"/></w:rPr><w:t>q</w:t></w:r></w:p>"#
        );
        let body = paragraph.repeat(40);
        let bytes = crate::tests::package(&body, "", page);
        let package =
            f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
        // The steps of the exact bottoms in 1/512 half-EMU, of the line and of the space after.
        let steps = |unit: TwipLengthUnit| match unit {
            TwipLengthUnit::Nearest4096ths => {
                (parts(line) * rest_per_part, parts(after) * rest_per_part)
            }
            TwipLengthUnit::HalfEmus => {
                let twip = Length::UNITS_PER_TWIP * rest_parts;
                (line * twip, after * twip)
            }
        };
        for target in crate::Target::all() {
            let profile = crate::profile::Profile::of(target).unwrap();
            let unit = profile.quirks().twip_length_unit;
            let dot = profile.device_dot().units();
            // A spaced exact line rounds its top and its height on their own where the target
            // rounds them so, and its height adds the same dots to each line.
            let parts_rounded = rule == "exact"
                && after > 0
                && profile.quirks().exact_spaced_bottom == ExactSpacedBottom::PartsRounded;
            // The dot of the exact bottom of the line of paragraph k, or of its exact top, a
            // half down the page.
            let dots = |unit: TwipLengthUnit, k: i64| {
                let (line, after) = steps(unit);
                let bottom = top * rest_parts + k * (line + after);
                let bottom = if parts_rounded { bottom } else { bottom + line };
                f_office_units::div_round(bottom, dot * rest_parts)
            };
            let moves = |unit: TwipLengthUnit| -> Vec<i64> {
                (0..40).map(|k| dots(unit, k) - dots(unit, 0)).collect()
            };
            // On the dot of a target that adds in whole parts, the two units put some of the
            // lines on other dots, so the case tells them apart there.
            let apart = moves(TwipLengthUnit::Nearest4096ths) != moves(TwipLengthUnit::HalfEmus);
            assert!(
                apart || unit == TwipLengthUnit::HalfEmus,
                "{rule} {line} {after} {target}"
            );
            let baselines = first_page_baselines(&package, target);
            assert_eq!(baselines.len(), 40, "{rule} {line} {after} {target}");
            let expected: Vec<i64> = moves(unit)
                .iter()
                .map(|moved| baselines[0] + moved * dot)
                .collect();
            assert_eq!(baselines, expected, "{rule} {line} {after} {target}");
            seen.push(unit);
        }
    }
    assert!(seen.contains(&TwipLengthUnit::Nearest4096ths));
    assert!(seen.contains(&TwipLengthUnit::HalfEmus));
}

/// The moves of the dots of `count` places, from the first: `first` lengths of `line` and then
/// one more for each place below `top`, in 1/512 half-EMU, on the dot `dot` of the same unit,
/// each to its nearest dot, a half down the page.
fn stack_moves(top: i64, (first, line): (i64, i64), dot: i64, count: i64) -> Vec<i64> {
    let dots = |k: i64| f_office_units::div_round(top + (k + first) * line, dot);
    (0..count).map(|k| dots(k) - dots(0)).collect()
}

/// Checks the baselines of a page of `count` exact lines of `twips` twips from the top margin
/// of 720 twips, laid out for `target`, against the dots of their deciding places in the
/// target's unit, in which a line is `parts` parts of 1/4096 pt, and returns the unit.
fn check_long_stack(
    package: &f_office_opc::Package,
    target: crate::Target,
    (twips, parts, count): (i64, i64, i64),
) -> crate::quirks::TwipLengthUnit {
    use crate::quirks::{ExactBaseline, TwipLengthUnit};
    let profile = crate::profile::Profile::of(target).unwrap();
    let quirks = profile.quirks();
    let dot = profile.device_dot().units();
    let height = twips * Length::UNITS_PER_TWIP;
    // The top gives the dot of a line whose box rounds down on a device that forms the box of
    // an exact line, and the bottom gives it otherwise.
    let tops = quirks.exact_baseline == ExactBaseline::BoxForms && (height % dot) * 2 < dot;
    let first = i64::from(!tops);
    let top = 720 * Length::UNITS_PER_TWIP * 512;
    let whole_parts = stack_moves(top, (first, parts * 3_175), dot * 512, count);
    let exactly = stack_moves(top, (first, height * 512), dot * 512, count);
    // The half-EMUs put each place on half a dot on the side of the rest too, so the two units
    // differ only where the long sum crosses half a dot.
    let unit = quirks.twip_length_unit;
    assert!(
        whole_parts != exactly || unit == TwipLengthUnit::HalfEmus,
        "{twips} {target}"
    );
    let baselines = first_page_baselines(package, target);
    assert_eq!(
        baselines.len(),
        usize::try_from(count).unwrap(),
        "{twips} {target}"
    );
    let expected = match unit {
        TwipLengthUnit::Nearest4096ths => whole_parts,
        TwipLengthUnit::HalfEmus => exactly,
    };
    let expected: Vec<i64> = expected
        .iter()
        .map(|moved| baselines[0] + moved * dot)
        .collect();
    assert_eq!(baselines, expected, "{twips} {target}");
    unit
}

#[test]
fn carries_a_long_sum_of_lengths_of_whole_twips_across_half_a_dot() {
    use crate::quirks::TwipLengthUnit;
    // A page of exact lines at 1 pt from the top margin of 720 twips, which lies on a whole dot
    // of each target, in two cases: 288 lines of 47 twips, which enter 0.4 part of 1/4096 pt
    // high each (9,625.6 parts), and whose boxes round up; and 330 lines of 41 twips, which
    // enter 0.2 part high (8,396.8 parts), and whose boxes round down. The exact places lie on
    // twelfths of a dot, and after about 103 and 205 lines the parts carry those a twelfth
    // short of half a dot past it, onto the dot below.
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="720" w:right="1440" w:bottom="1440" w:left="1440" w:header="360" w:footer="720"/>"#;
    let mut seen = Vec::new();
    for case in [(47, 9_626, 288), (41, 8_397, 330)] {
        let (twips, _, count) = case;
        let exact = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="{twips}" w:lineRule="exact"/></w:pPr><w:r><w:rPr><w:sz w:val="2"/></w:rPr><w:t>q</w:t></w:r></w:p>"#
        );
        let body = exact.repeat(usize::try_from(count).unwrap());
        let bytes = crate::tests::package(&body, "", page);
        let package =
            f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
        for target in crate::Target::all() {
            seen.push(check_long_stack(&package, target, case));
        }
    }
    assert!(seen.contains(&TwipLengthUnit::Nearest4096ths));
}

#[test]
fn starts_the_twips_rest_again_on_the_page_of_a_new_section() {
    use crate::quirks::TwipLengthUnit;
    // Three exact lines of 43 twips, a section that starts a new page with the same margins,
    // and forty exact lines of 43 twips on its page, from the top margin of 1 inch. On the new
    // page the exact bottoms lie exactly half a dot past a whole dot every 12 lines, as on the
    // first page of `adds_lengths_of_whole_twips_down_the_page_in_the_targets_unit`.
    let spacing = r#"<w:spacing w:before="0" w:after="0" w:line="43" w:lineRule="exact"/>"#;
    let run = r#"<w:r><w:rPr><w:sz w:val="2"/></w:rPr><w:t>q</w:t></w:r>"#;
    let margins = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let exact = format!("<w:p><w:pPr>{spacing}</w:pPr>{run}</w:p>");
    let end = format!(
        r#"<w:p><w:pPr>{spacing}<w:sectPr><w:type w:val="nextPage"/>{margins}</w:sectPr></w:pPr>{run}</w:p>"#
    );
    let body = format!("{}{end}{}", exact.repeat(2), exact.repeat(40));
    let bytes = crate::tests::package(&body, "", margins);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let top = 1440 * Length::UNITS_PER_TWIP * 512;
    let mut seen = Vec::new();
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let unit = profile.quirks().twip_length_unit;
        let dot = profile.device_dot().units();
        let line = match unit {
            TwipLengthUnit::Nearest4096ths => 8_806 * 3_175,
            TwipLengthUnit::HalfEmus => 43 * Length::UNITS_PER_TWIP * 512,
        };
        let moves = stack_moves(top, (1, line), dot * 512, 40);
        let baselines = page_baselines(&package, target, 1);
        assert_eq!(baselines.len(), 40, "{target}");
        let expected: Vec<i64> = moves
            .iter()
            .map(|moved| baselines[0] + moved * dot)
            .collect();
        assert_eq!(baselines, expected, "{target}");
        seen.push(unit);
    }
    assert!(seen.contains(&TwipLengthUnit::Nearest4096ths));
}

#[test]
fn carries_the_twips_rest_past_a_line_of_whole_4096ths() {
    use crate::quirks::{LineHeightUnit, TwipLengthUnit};
    // One line of single spacing at 1 pt, whose height is no length of whole twips, and below
    // it forty exact lines of 43 twips, from the top margin of 1 inch. On a target that holds
    // the single line in whole 1/4096 pt, it is 2,500 × 2 = 5,000 parts high and adds no error,
    // so the twips rest goes on below it. Added exactly, the exact bottoms would lie 0.006 dot
    // past half a dot after 8, 20 and 32 exact lines and take the dot below; with 0.4 part
    // lost for each exact line, they lie below the half and take the dot above.
    let single = r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="2"/></w:rPr><w:t>q</w:t></w:r></w:p>"#;
    let exact = r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="43" w:lineRule="exact"/></w:pPr><w:r><w:rPr><w:sz w:val="2"/></w:rPr><w:t>q</w:t></w:r></w:p>"#;
    let body = format!("{single}{}", exact.repeat(40));
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let bytes = crate::tests::package(&body, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let top = 1440 * Length::UNITS_PER_TWIP * 512 + 5_000 * 3_175;
    let mut tested = 0;
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let quirks = profile.quirks();
        if quirks.twip_length_unit != TwipLengthUnit::Nearest4096ths
            || quirks.line_height_unit != LineHeightUnit::Whole4096ths
        {
            continue;
        }
        let dot = profile.device_dot().units() * 512;
        let moves = |line: i64| -> Vec<i64> {
            let dots = |k: i64| f_office_units::div_round(top + (k + 1) * line, dot);
            (0..40).map(|k| dots(k) - dots(0)).collect()
        };
        let entered = moves(8_806 * 3_175);
        assert_ne!(
            entered,
            moves(43 * Length::UNITS_PER_TWIP * 512),
            "{target}"
        );
        let baselines: Vec<i64> = first_page_baselines(&package, target)
            .into_iter()
            .skip(1)
            .collect();
        assert_eq!(baselines.len(), 40, "{target}");
        let expected: Vec<i64> = entered
            .iter()
            .map(|moved| baselines[0] + moved * (dot / 512))
            .collect();
        assert_eq!(baselines, expected, "{target}");
        tested += 1;
    }
    assert!(tested > 0);
}

#[test]
fn carries_the_height_rest_from_row_to_row_of_a_table() {
    use crate::quirks::{LineHeightUnit, TwipLengthUnit};
    // The baselines of the glyph runs of `items`, also of the cells' lines in the groups that
    // clip them.
    fn baselines_in(items: &[Item], found: &mut Vec<i64>) {
        for item in items {
            match item {
                Item::Glyphs(run) => found.extend(run.glyphs.first().map(|g| g.y.units())),
                Item::Group(group) => baselines_in(&group.items, found),
                _ => {}
            }
        }
    }
    // A table of forty-eight rows at the top margin of 1 inch, each with one line of single
    // spacing at 11 pt and no borders or margins above or below. On a target that holds the
    // line in whole 1/4096 pt, each row is 2,500 × 22 = 55,000 parts high, 341,064.45
    // half-EMUs, and the line's box, whose height rounds up, places it by its bottom. The rows
    // carry that sum: the bottom of the 44th row's line lies past half a dot and takes the
    // dot below. Rows whose ends dropped the 0.45 half-EMU past their whole half-EMUs would
    // put that bottom below the half and take the dot above.
    let line = r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>q</w:t></w:r></w:p>"#;
    let row = format!(
        r#"<w:tr><w:tc><w:tcPr><w:tcW w:w="5000" w:type="dxa"/></w:tcPr>{line}</w:tc></w:tr>"#
    );
    let table = format!(
        r#"<w:tbl><w:tblPr><w:tblW w:w="5000" w:type="dxa"/><w:tblCellMar><w:top w:w="0" w:type="dxa"/><w:left w:w="108" w:type="dxa"/><w:bottom w:w="0" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr><w:tblGrid><w:gridCol w:w="5000"/></w:tblGrid>{}</w:tbl><w:p/>"#,
        row.repeat(48)
    );
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let bytes = crate::tests::package(&table, "", page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let top = 1440 * Length::UNITS_PER_TWIP * 512;
    let mut tested = 0;
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).unwrap();
        let quirks = profile.quirks();
        if quirks.twip_length_unit != TwipLengthUnit::Nearest4096ths
            || quirks.line_height_unit != LineHeightUnit::Whole4096ths
        {
            continue;
        }
        let dot = profile.device_dot().units() * 512;
        let moves = |row: i64| -> Vec<i64> {
            let dots = |k: i64| f_office_units::div_round(top + (k + 1) * row, dot);
            (0..48).map(|k| dots(k) - dots(0)).collect()
        };
        let carried = moves(55_000 * 3_175);
        assert_ne!(carried, moves(341_064 * 512), "{target}");
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Em2048, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        let mut baselines = Vec::new();
        baselines_in(list.pages()[0].items(), &mut baselines);
        baselines.truncate(48);
        assert_eq!(baselines.len(), 48, "{target}");
        let expected: Vec<i64> = carried
            .iter()
            .map(|moved| baselines[0] + moved * (dot / 512))
            .collect();
        assert_eq!(baselines, expected, "{target}");
        tested += 1;
    }
    assert!(tested > 0);
}

#[test]
fn adds_the_heights_of_lines_of_a_minimum_below_their_single_line_as_lines_of_single_spacing() {
    // Forty-eight one-line paragraphs at 11 pt, of single spacing, and the same of at-least
    // spacing with a minimum of 1 pt. The single line is 2,500 × 22 = 55,000 parts of
    // 1/4096 pt, 341,064.45 half-EMUs, and F-Office's own height 341,064. The two sums lie on
    // other dots at the bottom of the 44th line, so the at-least lines lie as the lines of
    // single spacing only when they add their heights in the same unit.
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let baselines = |spacing: &str, target| {
        let paragraph = format!(
            r#"<w:p><w:pPr><w:spacing w:after="0" {spacing}/></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>q</w:t></w:r></w:p>"#
        );
        let bytes = crate::tests::package(&paragraph.repeat(48), "", page);
        let package =
            f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let list = crate::layout(&package, (&Em2048, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        list.pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Glyphs(run) => run.glyphs.first().map(|g| g.y.units()),
                _ => None,
            })
            .collect::<Vec<i64>>()
    };
    for target in crate::Target::all() {
        let single = baselines(r#"w:line="240" w:lineRule="auto""#, target);
        assert_eq!(single.len(), 48, "{target}");
        assert_eq!(
            baselines(r#"w:line="20" w:lineRule="atLeast""#, target),
            single,
            "{target}"
        );
    }
}

#[test]
fn rounds_a_line_in_a_table_cell_with_its_space_after_where_the_target_holds_it() {
    use std::collections::BTreeSet;

    use crate::layout::testing::Fake;
    use crate::quirks::CellSpaceAfter;
    // A table cell 1 inch below the page's top, which lies on a whole dot of each target, holds
    // two one-line paragraphs of the fake font at 11 pt. The first has (160 + k) twips after,
    // k from 0 to 11, so that only its space after changes, through the twelve twips of 5 dots
    // of 0.12 pt. At 11 pt the ascent (73.33 dots) and the descent (18.33 dots) both round
    // down, so a box that holds the space after puts the line a dot lower where the space's
    // part of a dot gives the longer rounded height.
    let paragraph = |letter: char, after: i64| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="{after}" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:rPr><w:sz w:val="22"/></w:rPr><w:t>{letter}</w:t></w:r></w:p>"#
        )
    };
    let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
    let packages: Vec<Vec<u8>> = (0..12)
        .map(|k| {
            let cell = paragraph('a', 160 + k) + &paragraph('b', 0);
            let body = table("", &[4000], &[("", &[cell.as_str()])]) + "<w:p/>";
            crate::tests::package(&body, "", page)
        })
        .collect();
    let mut seen = Vec::new();
    for target in crate::Target::all() {
        let held = crate::profile::Profile::of(target)
            .unwrap()
            .quirks()
            .cell_space_after;
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let baselines: BTreeSet<i64> = packages
            .iter()
            .map(|bytes| {
                let limits = f_office_opc::Limits::default();
                let package = f_office_opc::Package::open(bytes, &limits).unwrap();
                let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
                    .unwrap()
                    .value;
                find(&list, 'a').2
            })
            .collect();
        match held {
            CellSpaceAfter::Outside => assert_eq!(baselines.len(), 1, "{target}"),
            CellSpaceAfter::Held => {
                assert_eq!(baselines.len(), 2, "{target}");
                assert_eq!(
                    baselines.last().unwrap() - baselines.first().unwrap(),
                    1,
                    "{target}"
                );
            }
        }
        seen.push(held);
    }
    assert!(seen.contains(&CellSpaceAfter::Outside));
    assert!(seen.contains(&CellSpaceAfter::Held));
}

#[test]
fn rounds_an_at_least_line_with_its_space_after_where_the_target_holds_it() {
    use crate::layout::testing::Fake;
    use crate::quirks::AtLeastSpaceAfter;
    // At the body's top, 1 inch below the page's top, which lies on a whole dot of each
    // target, a line of the fake font at 8.5 pt below an at-least minimum of 181 twips, above
    // a second paragraph. On a device of 0.12 pt, the ascent is 56.67 dots, the descent 14.17
    // and the minimum 75.42: the box rounds down, and 75 less the rounded descent, 14, puts
    // the baseline 61 dots below the top. With 6 pt (50 dots) of space after in the box, the
    // ascent part rounds the extra above the text, 4.58 dots, and the ascent each on its own,
    // 5 + 57 = 62, and the descent part is 125 - 50 - 14 = 61, so the baseline lies a dot
    // lower. The exact baseline, 61.25 dots, as one length would round to 61. The top lies
    // on 600 dots, so the move from 661 to 662 also crosses a whole `DOT` of the test.
    let baseline = |after: i64, target| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="{after}" w:line="181" w:lineRule="atLeast"/></w:pPr><w:r><w:rPr><w:sz w:val="17"/></w:rPr><w:t>a</w:t></w:r></w:p><w:p><w:r><w:t>b</w:t></w:r></w:p>"#
        );
        let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/>"#;
        let bytes = crate::tests::package(&body, "", page);
        let options = crate::Options {
            configuration: crate::Configuration::of(target),
            ..crate::Options::default()
        };
        let limits = f_office_opc::Limits::default();
        let package = f_office_opc::Package::open(&bytes, &limits).unwrap();
        let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value;
        find(&list, 'a').2
    };
    let mut seen = Vec::new();
    for target in crate::Target::all() {
        let held = crate::profile::Profile::of(target)
            .unwrap()
            .quirks()
            .at_least_space_after;
        let lower = baseline(120, target) - baseline(0, target);
        match held {
            AtLeastSpaceAfter::Outside => assert_eq!(lower, 0, "{target}"),
            AtLeastSpaceAfter::Held => assert_eq!(lower, 1, "{target}"),
        }
        seen.push(held);
    }
    assert!(seen.contains(&AtLeastSpaceAfter::Outside));
    assert!(seen.contains(&AtLeastSpaceAfter::Held));
}

#[test]
fn holds_the_space_after_of_an_at_least_line_of_single_spacing_where_the_device_holds_it() {
    use crate::layout::testing::{on_base_with, pass_with};
    use crate::numbering::Numbering;
    use crate::quirks::{AtLeastSpaceAfter, MultipleBaseline};
    // A line of the fake font at 10 pt above 6 pt of space after, below a minimum of 1 pt,
    // which is less than its single line, or of single automatic spacing. On the base device,
    // the ascent is 33.33 dots, the descent 8.33 and the single line 41.67. A box that holds
    // the space after, 25 dots, puts the baseline the descent part below its top: 67 - 25 - 8
    // = 34 dots, a dot below the rounded ascent, 33, which places the line where its box holds
    // no space.
    let baseline = |rule: &str, held: AtLeastSpaceAfter| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="120" {rule}/></w:pPr><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:t>a</w:t></w:r></w:p><w:p><w:r><w:t>b</w:t></w:r></w:p>"#
        );
        let target = on_base_with(|p| {
            p.with_variant(MultipleBaseline::DescentAboveExtra)
                .with_variant(held)
        });
        let dot = target.0.dots(1);
        let pass = pass_with(&body, ("", None), None, Numbering::default(), target);
        (pass.lines[0].baseline, dot)
    };
    let at_least = r#"w:line="20" w:lineRule="atLeast""#;
    let single = r#"w:line="240" w:lineRule="auto""#;
    let (held, dot) = baseline(at_least, AtLeastSpaceAfter::Held);
    assert_eq!(held, baseline(single, AtLeastSpaceAfter::Held).0);
    let (outside, _) = baseline(at_least, AtLeastSpaceAfter::Outside);
    assert_eq!(held - outside, dot);
}

#[test]
fn a_ligature_of_right_to_left_text_writes_the_letters_of_its_group_in_their_order() {
    use crate::quirks::ShapedGlyphText;
    // A beh and then a lam with an alef, in a right-to-left paragraph. The line draws the
    // ligature left of the beh, and the alef, a part of the ligature, before it; the ligature's
    // text is the lam and then the alef, and the beh keeps its own letter.
    let body = "<w:p><w:pPr><w:bidi/></w:pPr><w:r><w:rPr><w:rtl/></w:rPr><w:t>\u{0628}\u{0644}\u{0627}</w:t></w:r></w:p>";
    let texts = |value: ShapedGlyphText| {
        let (device, quirks) = on_base_with(|p| p.with_variant(value));
        let settings = crate::text::ShaperSettings::base_with(|p| p.with_variant(value));
        let pass = crate::layout::testing::pass_on(
            body,
            (NORMAL, None),
            None,
            Numbering::default(),
            (device, quirks, crate::layout::EarlierPass::default()),
            &(
                &crate::layout::testing::LamAlef as &dyn crate::Fonts,
                settings,
            ),
        );
        let mut texts = Vec::new();
        for item in pass.list.pages()[0].items() {
            if let Item::Glyphs(run) = item {
                for glyph in &run.glyphs {
                    let range = glyph.text_start as usize..glyph.text_end as usize;
                    texts.push((glyph.id, run.text.get(range).unwrap_or("").to_owned()));
                }
            }
        }
        texts
    };
    for value in [
        ShapedGlyphText::ClusterLetters,
        ShapedGlyphText::LowestMappedCharacter,
    ] {
        assert_eq!(
            texts(value),
            [
                (900, "\u{0644}\u{0627}".to_owned()),
                (0x0628, "\u{0628}".to_owned())
            ]
        );
    }
}

#[test]
fn east_asian_auto_space_uses_average_width_half_for_non_east_asian_faces() {
    use crate::layout::decisions::east_asian_auto_space;
    use crate::quirks::EastAsianAutoSpace;
    let size = Length::from_points(12).unwrap();
    let mut metrics = crate::FaceMetrics {
        units_per_em: 2048,
        average_width: 821,
        east_asian: false,
        ..crate::FaceMetrics::default()
    };
    let quarter = size.div_toward_zero(4);
    let expected_latin =
        Length::from_units(f_office_units::div_round(821 * size.units(), 2048)).div_toward_zero(2);

    let base = crate::profile::Profile::base();
    let default_quirks = base.with_variant(EastAsianAutoSpace::QuarterEm).quirks();
    let q = east_asian_auto_space(&default_quirks, size, &metrics, false);
    assert_eq!((q.advance, q.extra), (quarter, Length::ZERO));

    let win_quirks = base
        .with_variant(EastAsianAutoSpace::AverageWidthHalf)
        .quirks();
    let latin = east_asian_auto_space(&win_quirks, size, &metrics, false);
    assert_eq!(
        (latin.advance, latin.extra),
        (expected_latin, expected_latin)
    );

    // With w:balanceSingleByteDoubleByteWidth set, non-East-Asian faces also take 1/4 em.
    let balanced = east_asian_auto_space(&win_quirks, size, &metrics, true);
    assert_eq!((balanced.advance, balanced.extra), (quarter, quarter));

    // East Asian faces (e.g. Microsoft YaHei with average_width=987) still take 1/4 em, stepped
    // in whole dots on its own.
    metrics.east_asian = true;
    metrics.average_width = 987;
    let ea = east_asian_auto_space(&win_quirks, size, &metrics, false);
    assert_eq!((ea.advance, ea.extra), (quarter, quarter));

    // Non-East-Asian face with missing average_width falls back to 1/4 em.
    metrics.east_asian = false;
    metrics.average_width = 0;
    let fallback = east_asian_auto_space(&win_quirks, size, &metrics, false);
    assert_eq!((fallback.advance, fallback.extra), (quarter, quarter));
}