f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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
//! The pages of a body: their headers and footers.

use f_office_paint::DisplayList;

use crate::layout::testing::{Fake, filler, find, find_all, p};
use crate::testing::{WordParts, docx};
use crate::tests::{HEADER_REFERENCE, package};

#[test]
fn gives_the_page_after_a_continuous_section_break_the_default_header() {
    // The second section starts with a continuous break on page 1. It has `w:titlePg` and no
    // first-page header, and takes the default header from the section before. Its lines run
    // onto page 2, which is not its first page, so page 2 shows the default header.
    let end = format!("<w:p><w:pPr><w:sectPr>{HEADER_REFERENCE}</w:sectPr></w:pPr></w:p>");
    let body = p("a") + &end + &filler(70);
    let continuous = r#"<w:type w:val="continuous"/><w:titlePg/>"#;
    let bytes = package(&body, &p("h"), continuous);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let list = crate::layout(
        &package,
        (&Fake, &crate::ArtPictures::new()),
        &crate::Options::base(),
    )
    .unwrap()
    .value;
    let pages: Vec<usize> = find_all(&list, 'h').iter().map(|g| g.0).collect();
    assert_eq!(pages, [0, 1]);
}

/// The x in half-EMUs of the header's character `h` and of the body's character `b`, each
/// the first of a line indented `indent` twips, on a page `width` by `height` twips with
/// margins of one inch, for each target.
fn header_and_body_starts(width: i64, height: i64, indent: i64) -> Vec<(crate::Target, i64, i64)> {
    let line = |ch: char| {
        format!(r#"<w:p><w:pPr><w:ind w:left="{indent}"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#)
    };
    let page = format!(
        r#"{HEADER_REFERENCE}<w:pgSz w:w="{width}" w:h="{height}"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>"#
    );
    let bytes = package(&line('b'), &line('h'), &page);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    crate::Target::all()
        .map(|target| {
            let options = crate::Options {
                configuration: crate::Configuration::of(target),
                ..crate::Options::base()
            };
            let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
                .unwrap()
                .value;
            (target, find(&list, 'h').1, find(&list, 'b').1)
        })
        .collect()
}

#[test]
fn a_header_line_takes_the_writer_offset_of_its_page_as_a_body_line_does() {
    // A header is laid out on a story page with no end in height, but its text is written on
    // its page, so a header line and a body line with the same indent start at the same place
    // on every target. The indents move the start over the dots 1,541 across a page of 11,906
    // by 16,838 twips and 1,585 across a Letter page, where the PDF writer
    // of a target with the page form gives the factor of the page another count of steps than
    // its factor for other pages.
    let cases = [
        (11_906, 16_838, 2_250..2_270),
        (12_240, 15_840, 2_355..2_375),
    ]
    .into_iter()
    .flat_map(|(width, height, indents)| indents.map(move |indent| (width, height, indent)));
    for (width, height, indent) in cases {
        for (target, header, body) in header_and_body_starts(width, height, indent) {
            assert_eq!(header, body, "{target} {width} {indent}");
        }
    }
}

#[test]
fn starts_a_footer_at_its_exact_top_so_that_it_ends_without_a_height_rest() {
    // A first pass from 0 that ends 1,000 half-EMUs and a quarter of one down starts the footer
    // at the bottom less that, its rest the opposite quarter; one that ends half a half-EMU
    // short of 1,000 starts half a half-EMU past the bottom less 1,000, carried as the cursor
    // carries it. Without a rest the footer starts at the bottom less its height.
    use super::{REST_PARTS, footer_start};
    use f_office_units::Length;
    let units = Length::from_units;
    let ends = [
        (1_000, REST_PARTS / 4),
        (1_000, -REST_PARTS / 2),
        (1_000, 0),
    ];
    assert_eq!(
        ends.map(|(height, rest)| footer_start(units(9_000), (units(height), rest))),
        [
            (units(8_000), -REST_PARTS / 4),
            (units(8_001), -REST_PARTS / 2),
            (units(8_000), 0),
        ]
    );
}

/// The pages of a body whose 61st line holds the reference of a footnote of ten lines, `b` to
/// `k`, in one paragraph with the properties `props`, so that the footnote goes on to the next
/// page.
fn footnote_over_two_pages(props: &str) -> DisplayList {
    let lines: Vec<String> = ('b'..='k').map(|ch| format!("<w:t>{ch}</w:t>")).collect();
    let note = format!(
        r#"<w:footnote w:id="1"><w:p><w:pPr>{props}</w:pPr><w:r>{}</w:r></w:p></w:footnote>"#,
        lines.join("<w:br/>")
    );
    let reference =
        r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p>"#;
    let body = filler(60) + reference + &filler(10);
    let bytes = docx(&body)
        .plain_styles()
        .word_part("t0", "footnotes", "footnotes.xml", "footnotes", &note)
        .zip()
        .unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    crate::layout(
        &package,
        (&Fake, &crate::ArtPictures::new()),
        &crate::Options::base(),
    )
    .unwrap()
    .value
}

/// On `target`, with a style `Normal` of the paragraph properties `normal` and settings that
/// list no separators: the gap from the top of the rule of Word's own footnote separator to the
/// baseline of the footnote's character `n`, in device dots, and the rule's left edge less the
/// left edge of the body's character `a`, which takes `Normal`'s indent, in units, at the
/// device's places.
fn own_separator_gap(target: crate::Target, normal: &str) -> (i64, i64) {
    let note = r#"<w:footnote w:id="1"><w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="240" w:lineRule="auto"/><w:ind w:left="0"/></w:pPr><w:r><w:t>n</w:t></w:r></w:p></w:footnote>"#;
    let reference =
        r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p>"#;
    let styles = format!(
        r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:pPr>{normal}</w:pPr></w:style>"#
    );
    let bytes = docx(reference)
        .word_part("t0", "footnotes", "footnotes.xml", "footnotes", note)
        .word_part("t1", "styles", "styles.xml", "styles", &styles)
        .zip()
        .unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let options = crate::Options {
        configuration: crate::Configuration::of(target),
        device_places: true,
        ..crate::Options::base()
    };
    let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
        .unwrap()
        .value;
    let rule = list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            f_office_paint::Item::Rect(r) => Some(r),
            _ => None,
        })
        .unwrap();
    let (_, _, baseline) = find(&list, 'n');
    let (_, start, _) = find(&list, 'a');
    (
        baseline - rule.y.units() / crate::grid::DOT,
        rule.x.units() - start,
    )
}

#[test]
fn lays_out_words_own_separator_without_the_spacing_of_normal_where_the_target_drops_it() {
    use crate::quirks::OwnSeparatorSpacing;
    // `Normal` with 12 pt before, 10 pt after and 1.5 lines, and with no spacing; both indent
    // their paragraphs by one inch.
    let spaced = r#"<w:spacing w:before="240" w:after="200" w:line="360" w:lineRule="auto"/><w:ind w:left="1440"/>"#;
    let unspaced = r#"<w:ind w:left="1440"/>"#;
    for variant in [OwnSeparatorSpacing::Inherited, OwnSeparatorSpacing::Plain] {
        let target = target_where(|quirks| quirks.own_separator_spacing == variant);
        let (spaced_gap, spaced_left) = own_separator_gap(target, spaced);
        let (unspaced_gap, unspaced_left) = own_separator_gap(target, unspaced);
        // The separator takes `Normal`'s indent under both variants: its rule starts within a
        // twip of the indented text, at one place with and without the spacing.
        assert_eq!(spaced_left, unspaced_left, "{variant:?}");
        assert!(
            spaced_left.abs() < f_office_units::Length::UNITS_PER_TWIP,
            "{variant:?}"
        );
        match variant {
            // It also takes the 1.5 lines, which make its line taller.
            OwnSeparatorSpacing::Inherited => assert!(spaced_gap > unspaced_gap, "{variant:?}"),
            // It keeps single lines with nothing before or after.
            OwnSeparatorSpacing::Plain => assert_eq!(spaced_gap, unspaced_gap),
        }
    }
}

/// The page of the character `a` of a paragraph of double spacing after `lead` plain lines,
/// which brings a footnote of one line, in the compatibility mode `mode`.
fn page_of_a_line_with_its_footnote(lead: usize, mode: u32) -> usize {
    let note = r#"<w:footnote w:id="1"><w:p><w:r><w:t>n</w:t></w:r></w:p></w:footnote>"#;
    let reference = r#"<w:p><w:pPr><w:spacing w:line="480" w:lineRule="auto"/></w:pPr><w:r><w:t>a</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p>"#;
    let settings = format!(
        r#"<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="{mode}"/></w:compat>"#
    );
    let bytes = docx(&(filler(lead) + reference))
        .plain_styles()
        .word_part("t0", "footnotes", "footnotes.xml", "footnotes", note)
        .word_part("t1", "settings", "settings.xml", "settings", &settings)
        .zip()
        .unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let list = crate::layout(
        &package,
        (&Fake, &crate::ArtPictures::new()),
        &crate::Options::base(),
    )
    .unwrap()
    .value;
    find(&list, 'a').0
}

#[test]
fn needs_the_whole_height_of_a_line_above_its_own_footnote_in_every_mode() {
    // Below mode 15 a line above the footnotes of earlier lines needs only the room of its
    // text, but a line that brings a footnote goes to the next page at the same room as in
    // mode 15: where its footnote has no room below its whole height.
    let pages: Vec<(usize, usize, usize)> = (56..64)
        .map(|lead| {
            let at = |mode| page_of_a_line_with_its_footnote(lead, mode);
            (at(15), at(14), at(12))
        })
        .collect();
    assert!(pages.first().is_some_and(|p| p.0 == 0), "{pages:?}");
    assert!(pages.last().is_some_and(|p| p.0 == 1), "{pages:?}");
    assert!(pages.iter().all(|&(a, b, c)| a == b && b == c), "{pages:?}");
}

#[test]
fn gives_a_footnote_with_a_custom_mark_no_number() {
    let notes = concat!(
        r#"<w:footnote w:id="1"><w:p><w:r><w:t>*x</w:t></w:r></w:p></w:footnote>"#,
        r#"<w:footnote w:id="2"><w:p><w:r><w:footnoteRef/></w:r><w:r><w:t>y</w:t></w:r></w:p></w:footnote>"#,
    );
    let body = concat!(
        r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:footnoteReference w:customMarkFollows="1" w:id="1"/><w:t>*</w:t></w:r></w:p>"#,
        r#"<w:p><w:r><w:t>b</w:t></w:r><w:r><w:footnoteReference w:id="2"/></w:r></w:p>"#,
    );
    let bytes = docx(body)
        .plain_styles()
        .word_part("t0", "footnotes", "footnotes.xml", "footnotes", notes)
        .zip()
        .unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let list = crate::layout(
        &package,
        (&Fake, &crate::ArtPictures::new()),
        &crate::Options::base(),
    )
    .unwrap()
    .value;
    // The custom mark shows alone, and the next footnote is the first that takes a number: its
    // reference and the mark in its text show 1.
    assert_eq!(find_all(&list, '*').len(), 2);
    assert_eq!(find_all(&list, '1').len(), 2);
    assert_eq!(find_all(&list, '2'), []);
}

#[test]
fn cuts_a_shaded_footnote_over_two_pages_at_the_items_of_its_lines() {
    // Each part of the footnote holds the glyphs of its own lines, with a fill or without.
    let plain = footnote_over_two_pages("");
    let shaded =
        footnote_over_two_pages(r#"<w:shd w:val="clear" w:color="auto" w:fill="FF0000"/>"#);
    let glyphs = |list: &DisplayList| -> Vec<Vec<(usize, i64, i64)>> {
        ('b'..='k').map(|ch| find_all(list, ch)).collect()
    };
    let pages: Vec<usize> = glyphs(&plain)
        .iter()
        .flatten()
        .map(|glyph| glyph.0)
        .collect();
    assert!(pages.contains(&0) && pages.contains(&1), "{pages:?}");
    assert_eq!(glyphs(&shaded), glyphs(&plain));
}

/// The rectangles of the first page of a Letter document whose page borders are `borders`,
/// 24 pt from the page, laid out for the target `target`: x, y, width and height in hundredths
/// of a point, and the gray of the color.
fn page_border_rects(borders: &str, target: crate::Target) -> Vec<([i64; 4], u8)> {
    let section = format!(
        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" w:gutter="0"/><w:pgBorders w:offsetFrom="page">{borders}</w:pgBorders>"#
    );
    let bytes = package(&p("a"), &p("h"), &section);
    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::base()
    };
    let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
        .unwrap()
        .value;
    let hundredths = |length: f_office_units::Length| {
        length.units() * 100 / f_office_units::Length::UNITS_PER_POINT
    };
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Rect(r) => {
                Some(([r.x, r.y, r.width, r.height].map(hundredths), r.color.r))
            }
            _ => None,
        })
        .collect()
}

/// A target whose quirks pass `test`.
fn target_where(test: impl Fn(&crate::quirks::Quirks) -> bool) -> crate::Target {
    crate::Target::all()
        .find(|&target| test(&crate::profile::Profile::of(target).unwrap().quirks()))
        .unwrap()
}

/// The four sides of a page border of the style `style`, `w:sz` `eighths`, in black.
fn page_sides(style: &str, eighths: u32) -> String {
    ["top", "left", "bottom", "right"]
        .map(|side| {
            format!(r#"<w:{side} w:val="{style}" w:sz="{eighths}" w:space="24" w:color="000000"/>"#)
        })
        .concat()
}

/// The rectangles of a page border of `style` at 2.25 pt on a target that draws 3-D bands and
/// rounds page border lines down.
fn band_rects(style: &str) -> Vec<([i64; 4], u8)> {
    let bands = target_where(|quirks| {
        quirks.three_d_borders == crate::quirks::ThreeDBorders::Bands
            && quirks.page_border_lines == crate::quirks::PageBorderLines::Down
    });
    page_border_rects(&page_sides(style, 18), bands)
}

#[test]
fn draws_a_three_d_page_border_as_bands_across_the_top() {
    let rects = band_rects("threeDEmboss");
    // From the top: the light band 0.72 pt, the line 2.16 pt and the dark band 0.72 pt, each
    // running to the outer edge of the side's band of the same depth.
    assert!(rects.contains(&([2400, 2400, 56400, 72], 192)));
    assert!(rects.contains(&([2472, 2472, 56256, 216], 96)));
    assert!(rects.contains(&([2688, 2688, 55824, 72], 0)));
}

#[test]
fn nests_the_side_bands_of_a_three_d_page_border_below_the_top_bands() {
    let rects = band_rects("threeDEmboss");
    // The left side's bands start below the top's band of the same depth, in the same order
    // from the left.
    assert!(rects.contains(&([2400, 2472, 72, 74256], 192)));
    assert!(rects.contains(&([2472, 2688, 216, 73824], 96)));
    assert!(rects.contains(&([2688, 2760, 72, 73680], 0)));
}

#[test]
fn turns_the_bands_of_an_engraved_page_border_and_draws_one_line_where_3d_is_one_line() {
    // `threeDEngrave` turns the order: dark at the top and the left.
    assert!(band_rects("threeDEngrave").contains(&([2400, 2400, 56400, 72], 0)));
    // A target that draws 3-D borders as one line draws each side as one black line of its width.
    let one_line = target_where(|quirks| {
        quirks.three_d_borders == crate::quirks::ThreeDBorders::OneLine
            && quirks.page_border_lines == crate::quirks::PageBorderLines::Nearest
    });
    let base = page_border_rects(&page_sides("threeDEmboss", 18), one_line);
    assert!(base.contains(&([2400, 2400, 56400, 216], 0)));
    assert_eq!(base.len(), 4);
}

#[test]
fn rounds_a_page_border_line_down_to_whole_dots() {
    // A line of 1.5 pt is 12.5 dots of 0.12 pt: 12 dots where page border lines round down.
    let down =
        target_where(|quirks| quirks.page_border_lines == crate::quirks::PageBorderLines::Down);
    let rects = page_border_rects(&page_sides("single", 12), down);
    assert!(rects.contains(&([2400, 2400, 56400, 144], 0)));
    // `inset` and `outset` draw one line of their width.
    let inset = page_border_rects(&page_sides("inset", 12), down);
    assert_eq!(inset, rects);
}

#[test]
fn stacks_the_parts_of_a_page_border_in_whole_dots_from_its_outer_edges() {
    // `thinThickThinMediumGap` at 3 pt: thin lines and gaps of 1.5 pt, 12.5 dots of 0.12 pt,
    // and the line of 3 pt, 25 dots. Where page border lines round down, every part takes whole
    // dots, 12, 12, 25, 12 and 12, one after the other from each side's outer edge.
    let down =
        target_where(|quirks| quirks.page_border_lines == crate::quirks::PageBorderLines::Down);
    let rects = page_border_rects(&page_sides("thinThickThinMediumGap", 24), down);
    let across: Vec<[i64; 4]> = rects
        .iter()
        .filter(|(rect, _)| rect[2] == 56400)
        .map(|(rect, _)| *rect)
        .collect();
    assert_eq!(across.len(), 6);
    assert!(across.contains(&[2400, 2400, 56400, 144]));
    assert!(across.contains(&[2400, 2688, 56400, 300]));
    assert!(across.contains(&[2400, 3132, 56400, 144]));
    // The bottom side keeps the order of the parts from the top, and ends at its outer edge.
    let bottom = across.iter().map(|rect| rect[1] + rect[3]).max().unwrap();
    assert!(across.contains(&[2400, bottom - 144, 56400, 144]));
    assert!(across.contains(&[2400, bottom - 588, 56400, 300]));
    assert!(across.contains(&[2400, bottom - 876, 56400, 144]));
}

/// The top in half-EMUs of a shape centered on the margins with `wrap`, in the header or in
/// the body, before a paragraph that does or does not refer to a footnote of eight lines,
/// where the margins of a drawing count from `area`.
fn centered_shape_top(in_header: bool, wrap: &str, with_note: bool, area: &str) -> i64 {
    use crate::layout::testing::{AnchoredShape, shape_top};
    use crate::testing::Replaced as _;
    let shape = AnchoredShape {
        across: ("margin", 0),
        down: ("margin", 0),
        size: (914_400, 254_000),
        wrap,
        outline: Some(12_700),
        text: None,
    };
    let drawing = shape.drawing().replaced(
        "<wp:posOffset>0</wp:posOffset></wp:positionV>",
        "<wp:align>center</wp:align></wp:positionV>",
    );
    let drawing = format!("<w:p><w:r>{drawing}</w:r></w:p>");
    let reference = if with_note {
        r#"<w:r><w:footnoteReference w:id="1"/></w:r>"#
    } else {
        ""
    };
    let text = format!("<w:p><w:r><w:t>a</w:t></w:r>{reference}</w:p>");
    let mut parts = if in_header {
        docx(&format!("{text}<w:sectPr>{HEADER_REFERENCE}</w:sectPr>"))
            .word_part("h1", "header", "h1.xml", "hdr", &drawing)
    } else {
        docx(&format!("{drawing}{text}"))
    }
    .plain_styles();
    if with_note {
        let lines: Vec<String> = ('b'..='i').map(|ch| format!("<w:t>{ch}</w:t>")).collect();
        let note = format!(
            r#"<w:footnote w:id="1"><w:p><w:r>{}</w:r></w:p></w:footnote>"#,
            lines.join("<w:br/>")
        );
        parts = parts.word_part("t0", "footnotes", "footnotes.xml", "footnotes", &note);
    }
    let bytes = parts.zip().unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let options = crate::Options {
        overrides: crate::profile::Overrides::default().with_quirk("StoryMarginArea", area),
        ..crate::Options::base()
    };
    shape_top(
        &crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
            .unwrap()
            .value,
    )
}

#[test]
fn keeps_a_header_drawing_without_wrapping_above_the_footnotes_where_the_body_area_counts() {
    use crate::layout::testing::SQUARE_WRAP;
    // A shape of the header on a page whose footnote takes the body's end up. Where the area of
    // the body counts, a shape without wrapping centers above the footnotes and lies higher
    // than on a page without them; a shape that wraps the text keeps its place, as both do
    // where the section's margins count.
    let top =
        |wrap: &str, with_note: bool, area: &str| centered_shape_top(true, wrap, with_note, area);
    let unwrapped = "<wp:wrapNone/>";
    for area in ["SectionMargins", "BodyArea"] {
        assert_eq!(top(SQUARE_WRAP, true, area), top(SQUARE_WRAP, false, area));
    }
    assert_eq!(
        top(unwrapped, true, "SectionMargins"),
        top(unwrapped, false, "SectionMargins")
    );
    assert!(top(unwrapped, true, "BodyArea") < top(unwrapped, false, "BodyArea"));
}

#[test]
fn keeps_a_body_drawing_above_the_footnotes_found_on_its_page_where_the_body_area_counts() {
    use crate::layout::testing::SQUARE_WRAP;
    // A shape of the body, anchored before the reference of a footnote on the same page. Where
    // the area of the body counts, it centers above the footnotes, which only the pass after
    // the first knows when the shape is placed, with or without wrapping; where the section's
    // margins count, it keeps its place.
    let top =
        |wrap: &str, with_note: bool, area: &str| centered_shape_top(false, wrap, with_note, area);
    let unwrapped = "<wp:wrapNone/>";
    for wrap in [unwrapped, SQUARE_WRAP] {
        assert_eq!(
            top(wrap, true, "SectionMargins"),
            top(wrap, false, "SectionMargins")
        );
        assert!(top(wrap, true, "BodyArea") < top(wrap, false, "BodyArea"));
    }
    assert_eq!(
        top(unwrapped, true, "BodyArea"),
        top(SQUARE_WRAP, true, "BodyArea")
    );
}

/// The baseline of the body's character `a`, the one line of a section whose `w:vAlign` is
/// `align`, with a footnote referenced from that line when `note` holds, under the variant
/// `variant` of `AlignmentWithNotes`.
fn aligned_line(align: &str, note: bool, variant: &str) -> i64 {
    let footnote = r#"<w:footnote w:id="1"><w:p><w:r><w:t>n</w:t></w:r></w:p></w:footnote>"#;
    let reference = if note {
        r#"<w:r><w:footnoteReference w:id="1"/></w:r>"#
    } else {
        ""
    };
    let body = format!(
        r#"<w:p><w:r><w:t>a</w:t></w:r>{reference}</w:p><w:sectPr><w:vAlign w:val="{align}"/></w:sectPr>"#
    );
    let bytes = docx(&body)
        .plain_styles()
        .word_part("t0", "footnotes", "footnotes.xml", "footnotes", footnote)
        .zip()
        .unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let options = crate::Options {
        overrides: crate::profile::Overrides::default().with_quirk("AlignmentWithNotes", variant),
        ..crate::Options::base()
    };
    let list = crate::layout(&package, (&Fake, &crate::ArtPictures::new()), &options)
        .unwrap()
        .value;
    find(&list, 'a').2
}

#[test]
fn keeps_a_centered_page_with_a_footnote_at_the_top_where_the_target_does() {
    // Without a footnote, both variants center the line: it lies below the line of a page
    // whose section is top-aligned.
    let top = aligned_line("top", false, "AlignsPage");
    for variant in ["AlignsPage", "TopWithNotes"] {
        assert!(aligned_line("center", false, variant) > top, "{variant}");
        assert!(aligned_line("bottom", false, variant) > top, "{variant}");
    }
    // With a footnote, the plain reading centers the line in the room above the footnote, and
    // Word's variant keeps it at the top margin.
    let top_with_note = aligned_line("top", true, "AlignsPage");
    assert_eq!(top_with_note, top);
    for align in ["center", "bottom"] {
        assert!(aligned_line(align, true, "AlignsPage") > top, "{align}");
        assert_eq!(aligned_line(align, true, "TopWithNotes"), top, "{align}");
    }
}

/// The box of a path in hundredths of a point, with its fill color.
type PathBox = ([i64; 4], f_office_paint::Rgb);

/// The box of a group's clip in hundredths of a point, with the paths that the group holds.
type GroupBox = ([i64; 4], Vec<PathBox>);

/// The outline width of a group of stroked rectangles in half-EMUs, with the box of each of its
/// rectangles in hundredths of a point and its fill color.
type StrokedBox = (i64, Vec<PathBox>);

/// What the first page of a document with an art page border shows.
struct ArtPage {
    /// The box of each path in hundredths of a point, with its fill color.
    paths: Vec<PathBox>,
    /// The box of each group's clip, with the paths that the group holds.
    groups: Vec<GroupBox>,
    /// Each group of stroked rectangles, with its rectangles.
    stroked: Vec<StrokedBox>,
    /// Each warning's kind with its count.
    warnings: Vec<(&'static str, u32)>,
}

/// The box of the points of `commands` in hundredths of a point, or `None` when they have none.
fn hundredths_box(commands: &[f_office_paint::PathCommand]) -> Option<[i64; 4]> {
    let hundredths = |length: f_office_units::Length| {
        length.units() * 100 / f_office_units::Length::UNITS_PER_POINT
    };
    let mut points = commands
        .iter()
        .copied()
        .flat_map(|mut command| command.points_mut().map(|point| *point).collect::<Vec<_>>());
    let first = points.next()?;
    let mut bounds = [first.x, first.y, first.x, first.y];
    for point in points {
        bounds = [
            bounds[0].min(point.x),
            bounds[1].min(point.y),
            bounds[2].max(point.x),
            bounds[3].max(point.y),
        ];
    }
    Some(bounds.map(hundredths))
}

/// The box and color of each path of `items`.
fn path_boxes(items: &[f_office_paint::Item]) -> Vec<PathBox> {
    items
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Path(path) => Some((hundredths_box(&path.commands)?, path.color)),
            _ => None,
        })
        .collect()
}

/// The first page of a Letter document whose page border is `apples` at 16 pt on every side in
/// `color`, 24 pt from the page, laid out with the art pictures `pictures` for a target whose
/// quirk `ArtPageBorders` is `art`.
fn art_border_paths(
    pictures: &crate::ArtPictures,
    art: crate::quirks::ArtPageBorders,
    color: &str,
) -> ArtPage {
    let sides = ["top", "left", "bottom", "right"]
        .map(|side| {
            format!(r#"<w:{side} w:val="apples" w:sz="16" w:space="24" w:color="{color}"/>"#)
        })
        .concat();
    let section = format!(
        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" w:gutter="0"/><w:pgBorders w:offsetFrom="page">{sides}</w:pgBorders>"#
    );
    let bytes = package(&p("a"), &p("h"), &section);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let options = crate::Options {
        configuration: crate::Configuration::of(target_where(|quirks| {
            quirks.art_page_borders == art
        })),
        ..crate::Options::base()
    };
    let laid_out = crate::layout(&package, (&Fake, pictures), &options).unwrap();
    // The border is one group of the page's items, without a clip, whose every point the
    // writer places.
    let border: Vec<&[f_office_paint::Item]> = laid_out.value.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Group(group)
                if group.places == f_office_paint::GroupPlaces::Points && group.clip.is_none() =>
            {
                Some(group.items.as_slice())
            }
            _ => None,
        })
        .collect();
    assert!(border.len() <= 1, "one group for the border");
    let items = border.first().copied().unwrap_or_default();
    let paths = path_boxes(items);
    let groups = items
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Group(group) => Some((
                hundredths_box(&group.clip.as_ref()?.commands)?,
                path_boxes(&group.items),
            )),
            _ => None,
        })
        .collect();
    let hundredths = |length: f_office_units::Length| {
        length.units() * 100 / f_office_units::Length::UNITS_PER_POINT
    };
    let stroked = items
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Group(group) => match group.places {
                f_office_paint::GroupPlaces::Stroked { width } => Some((
                    width.units(),
                    group
                        .items
                        .iter()
                        .filter_map(|item| match item {
                            f_office_paint::Item::Rect(rect) => Some((
                                [
                                    hundredths(rect.x),
                                    hundredths(rect.y),
                                    hundredths(rect.x + rect.width),
                                    hundredths(rect.y + rect.height),
                                ],
                                rect.color,
                            )),
                            _ => None,
                        })
                        .collect(),
                )),
                _ => None,
            },
            _ => None,
        })
        .collect();
    let mut warnings: Vec<(&'static str, u32)> = laid_out
        .warnings
        .iter()
        .map(|(warning, count)| (warning.kind(), count))
        .collect();
    warnings.sort_unstable();
    ArtPage {
        paths,
        groups,
        stroked,
        warnings,
    }
}

/// Art pictures of `apples` at 16 pt: the whole square of each picture of the top side in
/// black, a run from corner to corner along the left side in black, and the top left corner's
/// square in red.
fn apples_pictures() -> crate::ArtPictures {
    let text = "f-office art pictures 3\n\
                style apples 16\n\
                part top repeat\n\
                shape 0 0 0 evenodd\n\
                ring 0 0 L 1000000 0 L 1000000 1000000 L 0 1000000\n\
                part left span\n\
                shape 0 0 0 nonzero\n\
                ring 0 0 L 1000000 0 L 1000000 1000000\n\
                part top-left corner\n\
                shape 255 0 0 nonzero\n\
                ring 0 0 Q 500000 0 1000000 1000000 C 0 1000000 0 500000 0 250000\n";
    let mut pictures = crate::ArtPictures::new();
    pictures.add(text.as_bytes()).unwrap();
    pictures
}

/// The blue of the sides of the art page border of the tests.
const ART_BLUE: f_office_paint::Rgb = f_office_paint::Rgb { r: 0, g: 0, b: 255 };

/// The boxes of the blue paths of `page` along the top side, from 24 pt to 39.96 pt down.
fn top_boxes(page: &ArtPage) -> Vec<[i64; 4]> {
    page.paths
        .iter()
        .filter(|(bounds, color)| *color == ART_BLUE && bounds[1] == 2400 && bounds[3] == 3996)
        .map(|(bounds, _)| *bounds)
        .collect()
}

#[test]
fn lays_the_pictures_of_an_art_side_between_corner_squares_of_whole_dots() {
    let page = art_border_paths(
        &apples_pictures(),
        crate::quirks::ArtPageBorders::Pictures,
        "0000FF",
    );
    assert_eq!(page.warnings, []);
    // The corner square is round(16 × 600 / 72) = 133 dots, 15.96 pt, from 24 pt. The top side
    // between the corners is 4434 dots: floor(4434 / 134) = 33 pictures of 134 dots, the last
    // 12 of them 135 dots, from 39.96 pt to 572.04 pt.
    let tops = top_boxes(&page);
    assert_eq!(tops.len(), 33);
    assert_eq!(
        [tops.first(), tops.get(20), tops.get(21), tops.last()],
        [
            Some(&[3996, 2400, 5604, 3996]),
            Some(&[36156, 2400, 37764, 3996]),
            Some(&[37764, 2400, 39384, 3996]),
            Some(&[55584, 2400, 57204, 3996]),
        ]
    );
}

#[test]
fn spans_an_art_side_from_corner_to_corner_and_keeps_the_colors_of_its_corner() {
    let page = art_border_paths(
        &apples_pictures(),
        crate::quirks::ArtPageBorders::Pictures,
        "0000FF",
    );
    let red = f_office_paint::Rgb { r: 255, g: 0, b: 0 };
    assert!(page.paths.contains(&([2400, 3996, 3996, 75204], ART_BLUE)));
    assert!(page.paths.contains(&([2400, 2400, 3996, 3996], red)));
    assert_eq!(page.paths.len(), 35);
}

#[test]
fn draws_the_shapes_of_a_clip_as_a_group_whose_clip_is_stretched_to_the_square() {
    let text = "f-office art pictures 3\n\
                style apples 16\n\
                part top-left corner\n\
                clip evenodd\n\
                ring 0 0 L 500000 0 L 500000 500000 L 0 500000\n\
                shape 0 0 0 nonzero\n\
                ring 0 0 L 1000000 0 L 1000000 1000000\n\
                end\n\
                shape 255 0 0 nonzero\n\
                ring 0 0 L 1000000 1000000 L 0 1000000\n";
    let mut pictures = crate::ArtPictures::new();
    pictures.add(text.as_bytes()).unwrap();
    let page = art_border_paths(&pictures, crate::quirks::ArtPageBorders::Pictures, "0000FF");
    // The square is 133 dots, 15.96 pt, from 24 pt: the clip covers its top left quarter, to
    // 24 pt + 7.98 pt.
    assert_eq!(
        page.groups,
        [(
            [2400, 2400, 3198, 3198],
            vec![([2400, 2400, 3996, 3996], ART_BLUE)]
        )]
    );
    let red = f_office_paint::Rgb { r: 255, g: 0, b: 0 };
    assert_eq!(page.paths, [([2400, 2400, 3996, 3996], red)]);
}

#[test]
fn draws_the_rectangles_of_a_picture_as_stroked_rectangles_of_their_width() {
    let text = "f-office art pictures 3\n\
                style apples 16\n\
                part top repeat\n\
                rect 0 0 0 250000 250000 750000 750000 140\n\
                part top-left corner\n\
                rect 255 0 0 0 0 500000 500000 280\n";
    let mut pictures = crate::ArtPictures::new();
    pictures.add(text.as_bytes()).unwrap();
    let page = art_border_paths(&pictures, crate::quirks::ArtPageBorders::Pictures, "0000FF");
    assert_eq!(page.paths, []);
    // The rectangles of the top side's 33 squares, black in the picture and so blue, join one
    // group of their width, 0.14 pt; the first square runs from 39.96 pt to 56.04 pt across and
    // from 24 pt to 39.96 pt down. The corner's red rectangle, of another width, has its own.
    let widths: Vec<_> = page
        .stroked
        .iter()
        .map(|(width, rects)| (*width, rects.len()))
        .collect();
    assert_eq!(widths, [(3_556, 33), (7_112, 1)]);
    assert_eq!(
        page.stroked[0].1.first(),
        Some(&([4398, 2799, 5202, 3597], ART_BLUE))
    );
    let red = f_office_paint::Rgb { r: 255, g: 0, b: 0 };
    assert_eq!(page.stroked[1].1, [([2400, 2400, 3198, 3198], red)]);
}

#[test]
fn draws_no_art_side_without_its_picture_or_on_a_target_that_does_not_draw_art() {
    use crate::quirks::ArtPageBorders;
    let page = art_border_paths(&crate::ArtPictures::new(), ArtPageBorders::Pictures, "auto");
    assert_eq!(
        (page.paths, page.warnings),
        (vec![], vec![("art-border-not-drawn", 1)])
    );
    let page = art_border_paths(&apples_pictures(), ArtPageBorders::NotDrawn, "auto");
    assert_eq!(page.paths, []);
    assert!(
        page.warnings
            .iter()
            .any(|(kind, _)| *kind == "value-not-supported"),
        "{:?}",
        page.warnings
    );
}