f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! The layout test harness: what the tests of the layout share. The fake fonts, the layout of
//! a body in one pass or in passes, the context of a test's pass, the builders of tables,
//! paragraphs and anchored shapes, and the finders of glyphs and rectangles in a display list.
//! The file is test code only (`#![cfg(test)]`).
#![cfg(test)]

use std::fmt::Write;

use f_office_fonts::{
    FamilyName, FontId, MathBars, MathCorner, MathLimitGaps, MathLimits, MathRadical,
    MathSkewedFraction, OutlineError,
};
use f_office_paint::{DisplayList, Item, Page, Painted, PathCommand};
use f_office_units::Length;
use f_office_xml::{Document, Limits};

use crate::body::{Body, Sections};
use crate::grid::DOT;
use crate::layout::line::height::{FromBottom, LineBox};
use crate::layout::{Context, EarlierPass, Layout, PartStory, SectionLayout, Stories};
use crate::mode::{CompatibilityMode, ModeRules};
use crate::ns::{A, W, WP, WPS};
use crate::numbering::Numbering;
use crate::profile::Profile;
use crate::quirks::BodyFieldResults;
use crate::reader::PartReader;
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::text::{Shaper, ShaperSettings};
use crate::{ChosenFace, FaceMetrics, Fonts, params};

/// Every face has an em of 1000 units, ascends 800 and descends 200, so 10 pt text has 10 pt
/// lines with the baseline 8 pt below the top. Glyphs are 500 units wide, and 600 when bold.
pub(super) struct Fake;

/// The fake fonts with a shaper that draws a lam with an alef after it as one glyph, 900,
/// 1,000 units wide, and every other character as its own glyph.
pub(super) struct LamAlef;

impl Fonts for LamAlef {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        Fake.face(family, bold, italic)
    }

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

    fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
        if glyph == 900 {
            return Some(1000);
        }
        Fake.advance(font, glyph)
    }

    fn shape(
        &self,
        _font: FontId,
        request: &f_office_fonts::ShapeRequest<'_>,
    ) -> Result<Vec<f_office_fonts::ShapedGlyph>, f_office_fonts::ShapeFailure> {
        let shaped = |glyph, advance, cluster| f_office_fonts::ShapedGlyph {
            glyph,
            advance,
            offset: (0, 0),
            cluster,
        };
        let mut glyphs = Vec::new();
        let mut chars = request.text.char_indices().peekable();
        while let Some((at, ch)) = chars.next() {
            if ch == '\u{0644}' && chars.next_if(|&(_, next)| next == '\u{0627}').is_some() {
                glyphs.push(shaped(900, 1000, at));
            } else {
                glyphs.push(shaped(u32::from(ch), 500, at));
            }
        }
        Ok(glyphs)
    }
}

/// The family that the fake fonts make for East Asian text.
pub(super) const EAST_ASIAN_FAKE: &str = "Fake Mincho";

/// [`Fake`] fonts whose hhea line has a gap of 100 of the em's 1000 units: the hhea line with
/// its gap is 1,100 units over a win line of 1,000, so the face's single line holds an external
/// leading of 100 units above its win ascent.
pub(super) struct Gapped;

impl Fonts for Gapped {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        let mut face = Fake.face(family, bold, italic)?;
        face.metrics.hhea_line_gap = 100;
        face.metrics.line_top = 900;
        Some(face)
    }

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

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

impl Fonts for Fake {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        Some(ChosenFace {
            font: FontId::from_index(u32::from(bold) + 2 * u32::from(italic)),
            metrics: FaceMetrics {
                units_per_em: 1000,
                hhea_ascender: 800,
                hhea_descender: -200,
                hhea_line_gap: 0,
                descent: 200,
                underline_position: -100,
                underline_thickness: 50,
                strikeout_position: 250,
                strikeout_thickness: 50,
                superscript_offset: 0,
                subscript_offset: 0,
                superscript_size: 0,
                subscript_size: 0,
                line_top: 800,
                script_top: 800,
                east_asian: family.is(EAST_ASIAN_FAKE),
                average_width: 500,
                target_units_per_em: None,
            },
            synthetic_bold: false,
            synthetic_italic: false,
            stands_in: false,
        })
    }

    fn glyph(&self, _font: FontId, ch: char) -> Option<u32> {
        Some(u32::from(ch))
    }

    fn advance(&self, font: FontId, _glyph: u32) -> Option<u16> {
        Some(if font.index() % 2 == 1 { 600 } else { 500 })
    }

    /// Only "V" followed by "A" kerns, by -100 units.
    fn kerning(&self, _font: FontId, left: u32, right: u32, _table: crate::KerningTable) -> i32 {
        if (left, right) == (u32::from('V'), u32::from('A')) {
            -100
        } else {
            0
        }
    }

    /// Only two glyphs have ink: DEEP, which reaches far below its baseline, and TALL, which
    /// reaches far above it.
    fn ink(&self, _font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
        Ok(match char::from_u32(glyph) {
            Some(DEEP) => Some((-900, 700)),
            Some(TALL) => Some((-100, 1900)),
            _ => None,
        })
    }
}

/// A character whose fake glyph's ink reaches 900 units below its baseline and 700 above.
pub(super) const DEEP: char = '\u{e000}';

/// A character whose fake glyph's ink reaches 100 units below its baseline and 1,900 above.
pub(super) const TALL: char = '\u{e001}';

/// [`Fake`] fonts with a `MATH` table whose `MathLeading` is 150 of the em's 1000 units: each
/// glyph has ink from 0 to 700 units, and the parentheses and the root sign, with ink from -250
/// to 750, have the vertical variants 8000 (1600 units tall, ink from -500 to 1100) and 8001
/// (2400 tall, ink from -900 to 1500). The radical's constants: a gap of 100, a bar 50 thick
/// with 50 over it, 50 before the degree and -300 after it, the degree at 60 % of the sign, and
/// a least element top of 600.
pub(super) struct FakeMath;

impl Fonts for FakeMath {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        Fake.face(family, bold, italic)
    }

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

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

    fn ink(&self, _font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
        Ok(Some(match glyph {
            0x28 | 0x29 | 0x221A => (-250, 750),
            0x2044 => (-200, 700),
            8000 => (-500, 1100),
            8001 => (-900, 1500),
            _ => (0, 700),
        }))
    }

    fn math_limits(&self, _font: FontId) -> Option<MathLimits> {
        Some(MathLimits {
            math_leading: 150,
            display_operator_min_height: 1300,
            upper_limit_baseline_rise_min: 250,
            lower_limit_baseline_drop_min: 500,
            superscript_baseline_drop_max: 290,
            subscript_baseline_drop_min: 200,
            delimited_sub_formula_min_height: 1465,
        })
    }

    fn math_radical(&self, _font: FontId) -> Option<MathRadical> {
        Some(MathRadical {
            vertical_gap: 100,
            rule_thickness: 50,
            extra_ascender: 50,
            kern_before_degree: 50,
            kern_after_degree: -300,
            degree_bottom_raise_percent: 60,
            flattened_accent_base_height: 600,
        })
    }

    fn math_skewed_fraction(&self, _font: FontId) -> Option<MathSkewedFraction> {
        Some(MathSkewedFraction {
            horizontal_gap: 400,
            vertical_gap: 100,
        })
    }

    fn math_limit_gaps(&self, _font: FontId) -> Option<MathLimitGaps> {
        Some(MathLimitGaps {
            lower_limit_gap_min: 100,
            upper_limit_gap_min: 100,
        })
    }

    fn math_stretch_stack(&self, _font: FontId) -> Option<f_office_fonts::MathStretchStack> {
        Some(f_office_fonts::MathStretchStack {
            top_shift_up: 800,
            bottom_shift_down: 600,
            gap_above_min: 100,
            gap_below_min: 100,
            min_connector_overlap: 100,
        })
    }

    fn vertical_variant(&self, _font: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
        if !matches!(glyph, 0x28 | 0x29 | 0x221A | 0x2044) {
            return None;
        }
        let base_height = if glyph == 0x2044 { 900 } else { 1000 };
        [(glyph, base_height), (8000, 1600), (8001, 2400)]
            .iter()
            .find(|&&(_, height)| height >= least)
            .map(|&(variant, _)| (variant, true))
            .or(Some((8001, false)))
    }
}

/// [`FakeMath`] fonts whose `MATH` table places scripts: the math italic x has an italic
/// correction of 100 units, a top right corner kern of 50 at every height and a bottom right
/// one of -300 below 100 units and -100 above, and the space after scripts is 200 units. Its radicals are [`FakeMath`]'s, and
/// its bars have gaps of 100 units and rules and extras of 50.
pub(super) struct FakeScripts;

impl Fonts for FakeScripts {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        FakeMath.face(family, bold, italic)
    }

    fn glyph(&self, font: FontId, ch: char) -> Option<u32> {
        FakeMath.glyph(font, ch)
    }

    fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
        FakeMath.advance(font, glyph)
    }

    fn ink(&self, font: FontId, glyph: u32) -> Result<Option<(i32, i32)>, OutlineError> {
        FakeMath.ink(font, glyph)
    }

    fn math_limits(&self, font: FontId) -> Option<MathLimits> {
        FakeMath.math_limits(font)
    }

    fn math_radical(&self, font: FontId) -> Option<MathRadical> {
        FakeMath.math_radical(font)
    }

    fn math_bars(&self, _font: FontId) -> Option<MathBars> {
        Some(MathBars {
            overbar_vertical_gap: 100,
            overbar_rule_thickness: 50,
            overbar_extra_ascender: 50,
            underbar_vertical_gap: 100,
            underbar_rule_thickness: 50,
            underbar_extra_descender: 50,
        })
    }

    fn vertical_variant(&self, font: FontId, glyph: u32, least: i32) -> Option<(u32, bool)> {
        FakeMath.vertical_variant(font, glyph, least)
    }

    fn italic_correction(&self, _font: FontId, glyph: u32) -> Option<i32> {
        (glyph == u32::from(MATH_X)).then_some(100)
    }

    fn math_kern(&self, _font: FontId, glyph: u32, corner: MathCorner, height: i32) -> Option<i32> {
        match corner {
            _ if glyph != u32::from(MATH_X) => None,
            MathCorner::TopRight => Some(50),
            MathCorner::BottomRight => Some(if height < 100 { -300 } else { -100 }),
            MathCorner::TopLeft | MathCorner::BottomLeft => None,
        }
    }

    fn space_after_script(&self, _font: FontId) -> Option<i32> {
        Some(200)
    }
}

/// The math italic small x (U+1D465), which an equation draws for x.
pub(super) const MATH_X: char = '\u{1D465}';

/// The default table style of most documents: 108 twip cell margins on the left and right.
pub(super) const NORMAL: &str = r#"<w:style w:type="table" w:default="1" w:styleId="TableNormal"><w:tblPr><w:tblCellMar><w:left w:w="108" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>"#;

pub(super) const SINGLE: &str = r#"w:val="single" w:sz="4""#;

pub(super) fn parse(xml: &str) -> Document {
    Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
}

/// No art pictures, as a caller that gives none.
static NO_ART: crate::ArtPictures = crate::ArtPictures::new();

/// No HTML div, as in a document without a web settings part.
static NO_DIVS: crate::web_settings::HtmlDivs<'static> = crate::web_settings::HtmlDivs::none();

/// The context of a test's pass: the styles and settings given, no HTML divs, no lists, notes
/// or comments, the base target's device and quirks, no date and no custom properties, no
/// earlier pass, and an ID of its own from the tests' one source of paragraph IDs
/// ([`crate::body::TEST_PARAGRAPH_IDS`]) for the label of a deleted cell's balloon.
pub(super) fn base_context<'a>(styles: &'a Styles, settings: &'a Settings) -> Context<'a> {
    Context {
        main: crate::testing::DOCUMENT,
        styles,
        settings,
        html_divs: &NO_DIVS,
        numbering: std::rc::Rc::default(),
        notes: std::rc::Rc::default(),
        endnotes: std::rc::Rc::default(),
        comments: std::rc::Rc::default(),
        device: crate::grid::base_device(),
        quirks: crate::grid::base_quirks(),
        now: None,
        file_name: None,
        properties: std::sync::Arc::default(),
        zone_minutes: 0,
        earlier: EarlierPass::default(),
        deleted_cell_label: crate::body::TEST_PARAGRAPH_IDS.next(),
        art: &NO_ART,
    }
}

/// Runs `test` on a layout of an empty default section, with default styles and settings and
/// the fake fonts, before any body.
pub(super) fn with_layout(test: impl FnOnce(&mut Layout<'_>)) {
    with_layout_on(Profile::clone, test);
}

/// Runs `test` as [`with_layout`] does, on the base target's profile with some quirks of
/// another variant (`change`), for a test that names the variant that it means.
pub(super) fn with_layout_on(
    change: impl FnOnce(&Profile) -> Profile,
    test: impl FnOnce(&mut Layout<'_>),
) {
    with_layout_of(&Fake, change, test);
}

/// Runs `test` as [`with_layout_on`] does, with the fonts `fonts` in place of the fake fonts.
pub(super) fn with_layout_of(
    fonts: &dyn Fonts,
    change: impl FnOnce(&Profile) -> Profile,
    test: impl FnOnce(&mut Layout<'_>),
) {
    let (styles, settings) = (Styles::default(), Settings::default());
    let (theme, table) = (Theme::default(), FontTable::default());
    let mut context = base_context(&styles, &settings);
    (context.device, context.quirks) = on_base_with(change);
    let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
    let stories = context.for_stories();
    let sections = Sections::one(SectionLayout::plain(&crate::body::Section::default(), 0));
    let mut layout = Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(fonts, &theme, &table, &shaper),
    );
    test(&mut layout);
}

pub(super) fn lay_out(body: &str, styles: &str, mode: Option<u32>) -> DisplayList {
    lay_out_with_header(body, styles, mode, None)
}

/// Lays out a body, with a header of the given blocks on every page.
pub(super) fn lay_out_with_header(
    body: &str,
    styles: &str,
    mode: Option<u32>,
    header: Option<&str>,
) -> DisplayList {
    pass_with_header(body, styles, mode, header).list
}

/// Lays out a body, with a header of the given blocks on every page, and gives the whole pass
/// with its records of the lines.
pub(super) fn pass_with_header(
    body: &str,
    styles: &str,
    mode: Option<u32>,
    header: Option<&str>,
) -> crate::layout::Pass {
    pass_with(
        body,
        (styles, mode),
        header,
        Numbering::default(),
        on_base(),
    )
}

/// The base target's layout device and quirks.
pub(super) fn on_base() -> (crate::grid::Device, crate::quirks::Quirks) {
    (crate::grid::base_device(), crate::grid::base_quirks())
}

/// The layout device and quirks of the base target's profile with some quirks of another
/// variant (`change`), for a test that names the variant that it means.
pub(super) fn on_base_with(
    change: impl FnOnce(&Profile) -> Profile,
) -> (crate::grid::Device, crate::quirks::Quirks) {
    let profile = change(&Profile::base());
    (profile.device(), profile.quirks())
}

/// The device with `dots` per inch and the quirks of the base target's profile with some
/// quirks of another variant (`change`), for tests of the device's arithmetic at other
/// resolutions.
pub(super) fn device_at(
    dots: i64,
    change: impl FnOnce(&Profile) -> Profile,
) -> crate::grid::Device {
    target_at(dots, change).0
}

/// The device of [`device_at`] with its quirks.
pub(super) fn target_at(
    dots: i64,
    change: impl FnOnce(&Profile) -> Profile,
) -> (crate::grid::Device, crate::quirks::Quirks) {
    let quirks = change(&Profile::base()).quirks();
    let device = crate::grid::Device::of(dots, &quirks).expect("a device dot");
    (device, quirks)
}

/// The lists of a numbering part with list 2: decimal labels of 20 pt at a left indent of 720
/// and a hanging indent of 360 twips.
pub(super) const LARGE_LABELS: &str = r#"<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:lvl></w:abstractNum><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>"#;

/// Lays out a body with the lists of a numbering part.
pub(super) fn lay_out_with_numbering(body: &str, numbering: &str) -> DisplayList {
    lay_out_with_numbering_on(body, numbering, on_base)
}

/// Lays out a body with the lists of a numbering part on the base target with one quirk's
/// variant.
pub(super) fn lay_out_with_numbering_as<Q: crate::quirks::Quirk + PartialEq>(
    body: &str,
    numbering: &str,
    variant: Q,
) -> DisplayList {
    lay_out_with_numbering_on(body, numbering, || {
        on_base_with(|p| p.with_variant(variant))
    })
}

/// Lays out a body with the lists of a numbering part on the device and quirks that `target`
/// makes.
fn lay_out_with_numbering_on(
    body: &str,
    numbering: &str,
    target: impl FnOnce() -> (crate::grid::Device, crate::quirks::Quirks),
) -> DisplayList {
    let doc = parse(numbering);
    let numbering = Numbering::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        crate::reader::settings::ReaderSettings::with_built_in_list(
            crate::quirks::BuiltInList::WithoutPart,
        ),
    );
    pass_with(body, ("", None), None, numbering, target()).list
}

/// Lays out a body with styles, a compatibility mode, a header and lists, on a device with
/// the target's quirks.
pub(super) fn pass_with(
    body: &str,
    styles_and_mode: (&str, Option<u32>),
    header: Option<&str>,
    numbering: Numbering,
    (device, quirks): (crate::grid::Device, crate::quirks::Quirks),
) -> crate::layout::Pass {
    let target = (device, quirks, EarlierPass::default());
    pass_after(body, styles_and_mode, header, numbering, target)
}

/// Lays out a body as `pass_with` does, in a pass that shows what an earlier pass found, such
/// as the wraps that start its pages.
pub(super) fn pass_after(
    body: &str,
    styles_and_mode: (&str, Option<u32>),
    header: Option<&str>,
    numbering: Numbering,
    target: (crate::grid::Device, crate::quirks::Quirks, EarlierPass),
) -> crate::layout::Pass {
    let fonts = (&Fake as &dyn Fonts, ShaperSettings::base());
    pass_on(body, styles_and_mode, header, numbering, target, &fonts)
}

/// Lays out a body as [`pass_after`] does, with the fonts and the settings of the shaper
/// `fonts` instead of the fake fonts and the base target's settings.
pub(super) fn pass_on(
    body: &str,
    styles_and_mode: (&str, Option<u32>),
    header: Option<&str>,
    numbering: Numbering,
    (device, quirks, earlier): (crate::grid::Device, crate::quirks::Quirks, EarlierPass),
    fonts: &(&dyn Fonts, ShaperSettings),
) -> crate::layout::Pass {
    let read = (body, styles_and_mode, header);
    in_passes(read, numbering, (device, quirks), *fonts, |pass| {
        pass(&earlier)
    })
}

/// Reads a body with its styles, its mode and its header once, and gives `run` a function that
/// lays it out in a pass that shows what an earlier pass found, so that the passes of a test
/// keep the paragraph IDs of one reading, as the library's passes do.
fn in_passes(
    (body, (styles, mode), header): (&str, (&str, Option<u32>), Option<&str>),
    numbering: Numbering,
    (device, quirks): (crate::grid::Device, crate::quirks::Quirks),
    (fonts, shaper): (&dyn Fonts, ShaperSettings),
    run: impl FnOnce(&dyn Fn(&EarlierPass) -> crate::layout::Pass) -> crate::layout::Pass,
) -> crate::layout::Pass {
    let header = header.map(|xml| {
        let doc = parse(&format!(r#"<w:hdr xmlns:w="{W}">{xml}</w:hdr>"#));
        crate::body::read_story(&mut PartReader::new(&doc), doc.root().unwrap())
    });
    let body_doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
    let mode_rules = ModeRules::of(CompatibilityMode::read(mode.map(i64::from)));
    let body = Body::read(
        &mut PartReader::new(&body_doc),
        body_doc.root().unwrap(),
        (
            crate::reader::settings::ReaderSettings::of(&quirks)
                .with_body_results(BodyFieldResults::ComputesFields),
            mode_rules,
        ),
    );
    // Empty defaults keep the spacing and run defaults of ECMA-376 that these tests expect,
    // unless the styles bring their own.
    let defaults = if styles.starts_with("<w:docDefaults>") {
        ""
    } else {
        "<w:docDefaults><w:rPrDefault/><w:pPrDefault/></w:docDefaults>"
    };
    let styles_doc = parse(&format!(
        r#"<w:styles xmlns:w="{W}">{defaults}{styles}</w:styles>"#
    ));
    let styles = Styles::read(
        &mut PartReader::new(&styles_doc),
        styles_doc.root().unwrap(),
    );
    let settings = Settings {
        mode_rules,
        ..Settings::default()
    };
    let theme = Theme::default();
    let table = FontTable::default();
    let headers = Stories {
        default: header.map(|blocks| PartStory {
            part: std::rc::Rc::from("word/header1.xml"),
            blocks: std::rc::Rc::from(blocks),
        }),
        ..Stories::default()
    };
    let sections = sections_of(&body, &headers);
    let pass = move |earlier: &EarlierPass| {
        let context = Context {
            numbering: std::rc::Rc::new(numbering.clone()),
            device,
            quirks,
            earlier: earlier.clone(),
            ..base_context(&styles, &settings)
        };
        let stories = context.for_stories();
        Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(fonts, &theme, &table, &shaper),
        )
        .run_with_wraps(&body)
    };
    run(&pass)
}

/// Lays out a body in passes, as the library does: each pass starts its pages with the wraps
/// of the pass before, places the later anchors that the passes before found and gives the
/// drawings of the body the footnotes of their page from the pass before, until the drawings
/// stay on their pages.
pub(super) fn passes(body: &str) -> crate::layout::Pass {
    passes_mode(body, None)
}

/// Lays out a body in passes under compatibility mode `mode` (`None` for the default mode 15).
pub(super) fn passes_mode(body: &str, mode: Option<u32>) -> crate::layout::Pass {
    let read = (body, (NORMAL, mode), None);
    let fonts = (&Fake as &dyn Fonts, ShaperSettings::base());
    in_passes(read, Numbering::default(), on_base(), fonts, |pass| {
        let first = pass(&EarlierPass::default());
        let mut earlier = EarlierPass {
            wraps: first.wraps,
            later_anchors: first.later_anchors,
            note_heights: first.note_heights,
            ..EarlierPass::default()
        };
        let mut last = pass(&earlier);
        for _ in 0..params::FURTHER_PASSES {
            let moved = earlier.wraps.after(&last.wraps);
            let grew = earlier.later_anchors.join(&last.later_anchors);
            if moved.is_none() && !grew && !last.notes_missed {
                break;
            }
            if let Some(next) = moved {
                earlier.wraps = next;
            }
            earlier.note_heights.clone_from(&last.note_heights);
            last = pass(&earlier);
        }
        last
    })
}

/// The sections of a body, each with the headers `headers` and without footers.
pub(super) fn sections_of(body: &Body, headers: &Stories) -> Sections<SectionLayout> {
    let sections = body.sections.try_map(|part| {
        Ok::<_, std::convert::Infallible>(SectionLayout {
            section: part.section,
            start: part.start,
            end: part.end,
            restarts_numbers: part.restarts_numbers,
            headers: headers.clone(),
            footers: Stories::default(),
            borders: part.borders,
            notes: part.notes.over(crate::note_setup::ByNoteKind::DEFAULT),
        })
    });
    sections.unwrap()
}

/// A table with one cell for each text in each row, on a grid of the given widths in twips.
pub(super) fn table(props: &str, grid: &[i64], rows: &[(&str, &[&str])]) -> String {
    let mut out = format!("<w:tbl><w:tblPr>{props}</w:tblPr><w:tblGrid>");
    for width in grid {
        write!(out, r#"<w:gridCol w:w="{width}"/>"#).unwrap();
    }
    out += "</w:tblGrid>";
    for (trpr, cells) in rows {
        write!(out, "<w:tr><w:trPr>{trpr}</w:trPr>").unwrap();
        for cell in *cells {
            write!(out, "<w:tc>{cell}</w:tc>").unwrap();
        }
        out += "</w:tr>";
    }
    out + "</w:tbl>"
}

pub(super) fn p(text: &str) -> String {
    format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>")
}

/// `lines` paragraphs of one short line each, which fill the first page from its top.
pub(super) fn filler(lines: usize) -> String {
    (0..lines).map(|_| p("q")).collect()
}

/// A paragraph with `marks` in its properties.
pub(super) fn marked(marks: &str, text: &str) -> String {
    format!("<w:p><w:pPr>{marks}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
}

/// A paragraph kept with the next one.
pub(super) fn kept(text: &str) -> String {
    marked("<w:keepNext/>", text)
}

/// The page of the first glyph of each character.
pub(super) fn pages(body: &str, styles: &str, chars: &str) -> Vec<usize> {
    let list = lay_out(body, styles, Some(15));
    chars.chars().map(|ch| find(&list, ch).0).collect()
}

/// The square wrap on both sides, of the anchored shapes of the tests.
pub(super) const SQUARE_WRAP: &str = r#"<wp:wrapSquare wrapText="bothSides"/>"#;

/// A rectangle that a paragraph anchors (`wp:anchor` of a `wps:wsp`), as the tests write one:
/// in front of the text and with no distances.
#[derive(Clone, Copy)]
pub(super) struct AnchoredShape<'a> {
    /// What the place across counts from (`relativeFrom`), and the offset from it in EMU.
    pub(super) across: (&'a str, i64),
    /// What the place down counts from, and the offset from it in EMU.
    pub(super) down: (&'a str, i64),
    /// The width and the height in EMU.
    pub(super) size: (i64, i64),
    /// The wrap element, such as [`SQUARE_WRAP`] or `<wp:wrapNone/>`.
    pub(super) wrap: &'a str,
    /// The width in EMU of a black outline, or none.
    pub(super) outline: Option<i64>,
    /// The text box, or none for a shape without text.
    pub(super) text: Option<ShapeText<'a>>,
}

/// The text box of an [`AnchoredShape`].
#[derive(Clone, Copy)]
pub(super) struct ShapeText<'a> {
    /// The blocks of `w:txbxContent`.
    pub(super) blocks: &'a str,
    /// The `wps:bodyPr` element, with the insets and the anchor of the text.
    pub(super) body: &'a str,
}

impl AnchoredShape<'_> {
    /// The `w:drawing` element of the shape, for the run that holds it.
    pub(super) fn drawing(self) -> String {
        let ((across, x), (down, y)) = (self.across, self.down);
        let (width, height) = self.size;
        let wrap = self.wrap;
        let line = self.outline.map_or(String::new(), |width| {
            format!(
                r#"<a:ln w="{width}"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>"#
            )
        });
        let text = self.text.map_or("<wps:bodyPr/>".to_owned(), |text| {
            format!(
                "<wps:txbx><w:txbxContent>{}</w:txbxContent></wps:txbx>{}",
                text.blocks, text.body
            )
        });
        format!(
            r#"<w:drawing><wp:anchor xmlns:wp="{WP}" behindDoc="0" distL="0" distR="0" distT="0" distB="0"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="{across}"><wp:posOffset>{x}</wp:posOffset></wp:positionH><wp:positionV relativeFrom="{down}"><wp:posOffset>{y}</wp:posOffset></wp:positionV><wp:extent cx="{width}" cy="{height}"/>{wrap}<a:graphic xmlns:a="{A}"><a:graphicData><wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/>{line}</wps:spPr>{text}</wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing>"#
        )
    }
}

/// A device dot position from twips, rounded as layout rounds.
pub(super) fn du(twips: i64) -> i64 {
    f_office_units::div_round(twips * Length::UNITS_PER_TWIP, DOT)
}

/// The baseline in device dots of a line of the fake font at 10 pt whose top is at `top`
/// twips. The single line of 10 pt (41.67 device dots) rounds up, so the baseline sits the
/// descent of 2 pt, rounded to 8 device dots, above the bottom of the line.
pub(super) fn base(top: i64) -> i64 {
    let text = 200 * Length::UNITS_PER_TWIP - 8 * DOT;
    f_office_units::div_round(top * Length::UNITS_PER_TWIP + text, DOT)
}

/// Where the first glyph of a character is: its page, its x in units and its baseline in
/// device dots.
pub(super) fn find(list: &DisplayList, ch: char) -> (usize, i64, i64) {
    find_all(list, ch)[0]
}

/// Where each glyph of a character is, in the order of painting, also inside a group: its
/// page, its x in units and its baseline in device dots.
pub(super) fn find_all(list: &DisplayList, ch: char) -> Vec<(usize, i64, i64)> {
    let mut out = Vec::new();
    for (page, painted) in list.pages().iter().map(Page::painted).enumerate() {
        for item in painted {
            let Painted::Glyphs(run) = item else { continue };
            for glyph in &run.glyphs {
                let text = run.glyph_text(glyph).unwrap();
                if text.starts_with(ch) {
                    out.push((page, glyph.x.units(), glyph.y.units() / DOT));
                }
            }
        }
    }
    out
}

/// Where a character first is, in whole device dots ([`x_du`]): its x and its baseline.
pub(super) fn at(list: &DisplayList, ch: char) -> (i64, i64) {
    let (_, x, y) = find(list, ch);
    (x_du(x), y)
}

/// The rectangles of a page in device dots: x, y, width and height.
pub(super) fn rects(list: &DisplayList, page: usize) -> Vec<(i64, i64, i64, i64)> {
    list.pages()[page]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some(
                [r.x, r.y, r.width, r.height]
                    .map(|v| v.units() / DOT)
                    .into(),
            ),
            Item::Glyphs(_)
            | Item::Path(_)
            | Item::Gradient(_)
            | Item::Image(_)
            | Item::Group(_) => None,
        })
        .collect()
}

/// The top of the highest shape on the first page, in units.
pub(super) fn shape_top(list: &DisplayList) -> i64 {
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(rect) => Some(rect.y.units()),
            Item::Path(path) => path
                .commands
                .iter()
                .filter_map(|c| match c {
                    PathCommand::MoveTo(p) | PathCommand::LineTo(p) => Some(p.y.units()),
                    _ => None,
                })
                .min(),
            Item::Glyphs(_) | Item::Gradient(_) | Item::Image(_) | Item::Group(_) => None,
        })
        .min()
        .unwrap()
}

pub(super) fn x_du(units: i64) -> i64 {
    units / DOT
}

/// The x in whole device dots, as [`x_du`] gives it, of a line whose text edge is at `edge`
/// twips and whose indent is `indent` twips: the edge rounds to the device grid and the indent
/// is added as it is.
pub(super) fn indented(edge: i64, indent: i64) -> i64 {
    x_du(du(edge) * DOT + indent * Length::UNITS_PER_TWIP)
}

/// The box of a line whose text goes `ascent` above and `descent` below its baseline, `height`
/// tall with a text line of that height, and its baseline `baseline` below its top: no rule of
/// single or multiple spacing places its baseline, the page does not place it up from its
/// bottom, and it holds no space after.
pub(super) fn plain_line_box(
    (ascent, descent): (Length, Length),
    height: Length,
    baseline: Length,
) -> LineBox {
    LineBox {
        ascent,
        descent,
        height,
        text_height: height,
        baseline,
        text_bottom: baseline + descent,
        single: false,
        from_bottom: FromBottom::No,
        multiple: false,
        after: Length::ZERO,
        top_room: Length::ZERO,
        rest: 0,
        twips: None,
        centered: None,
        grid_ties: None,
    }
}