f-office 0.3.0

Renders Office Open XML documents the way Microsoft Office does.
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
//! Layout tests of floating drawings, text boxes, shapes, frames and floating tables.

use f_office_paint::{Item, PathCommand};

use super::{
    CARLITO_RUN, RELATIONSHIPS, SECTION, anchored_at, carlito_line, compatibility_mode, docx,
    lines, para, placed, points, render, text_box,
};

#[test]
fn counts_a_drawing_from_above_the_own_space_before_of_its_paragraph() {
    // A text box 36 pt tall, 36 pt below the top of a paragraph with 12 pt before, which
    // wraps top and bottom. The paragraph's top lies 12 pt above its line, right below
    // "Alpha", so the box covers the start of "Next", whose 6 pt before stays below the box.
    let place = r#"<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>457200</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="457200"/><wp:wrapTopAndBottom/>"#;
    let anchor = format!(
        r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr>{}<w:r>{CARLITO_RUN}<w:t>Anchor</w:t></w:r></w:p>"#,
        text_box(place)
    );
    let next = para("Next").replacen(
        "<w:p>",
        r#"<w:p><w:pPr><w:spacing w:before="120"/></w:pPr>"#,
        1,
    );
    let body = format!(
        "{}{anchor}{next}<w:sectPr>{SECTION}</w:sectPr>",
        para("Alpha")
    );
    let page = &lines(&render(&docx(&body, &[], "")))[0];
    let y = |text: &str| page.iter().find(|(_, t)| t == text).unwrap().0;
    let (_, line) = carlito_line();
    // The box spans from one line plus 36 pt to one line plus 72 pt below the top of "Alpha".
    let gap = y("Next") - y("Alpha");
    assert!((gap - (line + 72.0 + 6.0)).abs() <= 0.25, "{gap} {page:?}");
}

#[test]
fn starts_the_body_below_a_drawing_of_the_header_that_wraps_top_and_bottom() {
    // A text box from 24 pt to 60 pt down the page, which reaches 24 pt into the body.
    let place = anchored_at("page", 0, 304_800);
    let head = format!(
        "<w:p>{}</w:p>",
        text_box(&format!(
            r#"{place}<wp:extent cx="1270000" cy="457200"/><wp:wrapTopAndBottom/>"#
        ))
    );
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/>{SECTION}</w:sectPr>"#,
        para("Body")
    );
    let page = &lines(&render(&docx(&body, &[("h1", &head)], "")))[0];
    let (ascent, _) = carlito_line();
    let (y, _) = page.iter().find(|(_, t)| t == "Body").unwrap();
    assert!((y - (60.0 + ascent)).abs() <= 0.25, "{page:?}");
}

#[test]
fn keeps_the_empty_lines_of_a_header_of_more_paragraphs_over_its_drawing() {
    // A text box from the top of the header's first paragraph, 12 pt down the page, to 48 pt
    // down, which wraps top and bottom.
    let place = r#"<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="457200"/><wp:wrapTopAndBottom/>"#;
    let mark = format!("<w:pPr>{CARLITO_RUN}</w:pPr>");
    let anchor = format!("<w:p>{mark}{}</w:p>", text_box(place));
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/>{SECTION}</w:sectPr>"#,
        para("Body")
    );
    let (ascent, line) = carlito_line();
    let body_at = |head: &str| {
        let page = &lines(&render(&docx(&body, &[("h1", head)], "")))[0];
        page.iter().find(|(_, t)| t == "Body").unwrap().0
    };
    // A lone empty paragraph goes below the box, and the body below that paragraph.
    let alone = body_at(&anchor);
    assert!((alone - (48.0 + line + ascent)).abs() <= 0.25, "{alone}");
    // With a second paragraph, both empty lines stay at the top of the header, and only the
    // box's wrap keeps the body out.
    let two = body_at(&format!("{anchor}<w:p>{mark}</w:p>"));
    assert!((two - (48.0 + ascent)).abs() <= 0.25, "{two}");
}

#[test]
fn puts_a_line_without_room_beside_a_tight_drawing_below_its_box() {
    // A text box across the page from 36 pt to 72 pt down, whose wrap polygon covers only its
    // upper half.
    let place = anchored_at("page", 0, 457_200);
    let drawing = text_box(&format!(
        r#"{place}<wp:extent cx="3810000" cy="457200"/><wp:wrapTight><wp:wrapPolygon edited="0"><wp:start x="0" y="0"/><wp:lineTo x="21600" y="0"/><wp:lineTo x="21600" y="10800"/><wp:lineTo x="0" y="10800"/></wp:wrapPolygon></wp:wrapTight>"#
    ));
    let body = format!(
        r"<w:p>{drawing}<w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let page = &lines(&render(&docx(&body, &[], "")))[0];
    let (ascent, _) = carlito_line();
    let (y, _) = page.iter().find(|(_, t)| t == "Body").unwrap();
    assert!((y - (72.0 + ascent)).abs() <= 0.25, "{page:?}");
}

#[test]
fn keeps_the_text_before_an_anchor_out_of_a_drawing_placed_from_the_page() {
    // A text box 108 pt wide from the left page edge and from 36 pt to 72 pt down, which the
    // second paragraph anchors. The text flows to its right.
    let place = anchored_at("page", 0, 457_200);
    let drawing = text_box(&format!(
        r#"{place}<wp:extent cx="1371600" cy="457200"/><wp:wrapSquare wrapText="bothSides"/>"#
    ));
    let body = format!(
        r"{}<w:p>{drawing}<w:r>{CARLITO_RUN}<w:t>Beta</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>",
        para("Alpha")
    );
    let page = &placed(&render(&docx(&body, &[], "")))[0];
    let x = |text: &str| page.iter().find(|(_, _, t)| t.trim() == text).unwrap().0;
    assert!((x("Alpha") - 108.0).abs() <= 0.25, "{page:?}");
    assert!((x("Beta") - 108.0).abs() <= 0.25, "{page:?}");
}

/// A table of one cell with "Cell", `width` twips wide, with the floating place `placement`.
fn floating_table(placement: &str, width: i64) -> String {
    format!(
        r#"<w:tbl><w:tblPr><w:tblpPr {placement}/></w:tblPr><w:tblGrid><w:gridCol w:w="{width}"/></w:tblGrid><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>"#,
        para("Cell")
    )
}

#[test]
fn places_a_floating_table_on_the_page_without_moving_the_text() {
    // 144 pt from the left edge and 100 pt from the top of the page, 72 pt wide.
    let table = floating_table(
        r#"w:vertAnchor="page" w:horzAnchor="page" w:tblpX="2880" w:tblpY="2000""#,
        1440,
    );
    let body = format!(
        "{}{table}{}<w:sectPr>{SECTION}</w:sectPr>",
        para("Before"),
        para("After")
    );
    let page = &placed(&render(&docx(&body, &[], "")))[0];
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    let (ascent, line) = carlito_line();
    // The cell text starts at the table's place, and the text after the table follows the
    // text before it.
    let cell = at("Cell");
    assert!((cell.0 - 144.0).abs() < 0.25, "{page:?}");
    assert!((cell.1 - 100.0 - ascent).abs() <= 0.25, "{page:?}");
    assert!(
        (at("After").1 - at("Before").1 - line).abs() <= 0.25,
        "{page:?}"
    );
}

#[test]
fn keeps_a_full_width_table_that_hangs_on_the_text_in_the_flow() {
    // As wide as the 228 pt text area, 10 pt below its place in the text.
    let table = floating_table(r#"w:vertAnchor="text" w:tblpY="200""#, 4560);
    let body = format!(
        "{}{table}{}<w:sectPr>{SECTION}</w:sectPr>",
        para("Before"),
        para("After")
    );
    let page = &placed(&render(&docx(&body, &[], "")))[0];
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    let (_, line) = carlito_line();
    let (before, cell, after) = (at("Before"), at("Cell"), at("After"));
    assert!((cell.1 - before.1 - line - 10.0).abs() <= 0.25, "{page:?}");
    // The text after the table comes below it.
    assert!(after.1 > cell.1 + line - 0.25, "{page:?}");
}

#[test]
fn places_a_framed_page_number_beside_the_next_paragraph() {
    let footer = format!(
        r#"<w:p><w:pPr><w:framePr w:wrap="around" w:vAnchor="text" w:hAnchor="margin" w:xAlign="right" w:y="0"/></w:pPr><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="begin"/></w:r><w:r>{CARLITO_RUN}<w:instrText>PAGE</w:instrText></w:r><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="end"/></w:r></w:p>{}"#,
        para("Foot")
    );
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:footerReference w:type="default" r:id="f1"/>{SECTION}</w:sectPr>"#,
        para("Body")
    );
    let list = render(&docx(&body, &[("f1", &footer)], ""));
    let page = &lines(&list)[0];
    // The number stands on the footer's only line, at the right margin.
    assert_eq!(page.len(), 2, "{page:?}");
    let glyphs: Vec<(String, f64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) => Some((run.text.clone(), points(run.glyphs[0].x.units()))),
            _ => None,
        })
        .collect();
    let number = glyphs.iter().find(|(t, _)| t == "1").unwrap();
    assert!(number.1 > 250.0, "{glyphs:?}");
    let foot = glyphs.iter().find(|(t, _)| t == "Foot").unwrap();
    assert!((foot.1 - 36.0).abs() < 0.25, "{glyphs:?}");
}

#[test]
fn places_an_anchored_text_box_without_moving_the_text() {
    let shape = format!(
        r#"<mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><mc:Choice Requires="wps"><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><wp:anchor behindDoc="0"><wp:positionH relativeFrom="page"><wp:posOffset>1270000</wp:posOffset></wp:positionH><wp:positionV relativeFrom="page"><wp:posOffset>1270000</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="635000"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>Box</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr lIns="25400" tIns="50800" rIns="0" bIns="0"/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></mc:Choice><mc:Fallback/></mc:AlternateContent>"#
    );
    let body = format!(
        r"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r><w:r>{shape}</w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let list = render(&docx(&body, &[], ""));
    let page = &lines(&list)[0];
    let texts: Vec<&str> = page.iter().map(|(_, t)| t.as_str()).collect();
    assert_eq!(texts, ["Body", "Box"], "{page:?}");
    let (ascent, _) = carlito_line();
    // The box's top edge is 100 pt down the page, and its text starts inside its insets of
    // 2 pt at the left and 4 pt at the top.
    assert!((page[1].0 - (104.0 + ascent)).abs() <= 0.12, "{page:?}");
    let x = list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Glyphs(run) if run.text == "Box" => Some(points(run.glyphs[0].x.units())),
            _ => None,
        })
        .unwrap();
    assert!((x - 102.0).abs() <= 0.12, "{x}");
    // The body text stays where it was.
    assert!((page[0].0 - (36.0 + ascent)).abs() <= 0.12, "{page:?}");
}

/// A floating shape without text at 100 pt from the page's top left corner, 100 by 50 pt,
/// with these shape properties: behind the text with no wrap, or in front of it with square
/// wrap.
fn floating_shape(behind: bool, props: &str) -> String {
    let wrap = if behind {
        "<wp:wrapNone/>"
    } else {
        "<wp:wrapSquare/>"
    };
    let behind = u8::from(behind);
    format!(
        r#"<w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:anchor behindDoc="{behind}"><wp:positionH relativeFrom="page"><wp:posOffset>1270000</wp:posOffset></wp:positionH><wp:positionV relativeFrom="page"><wp:posOffset>1270000</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="635000"/>{wrap}<a:graphic><a:graphicData><wps:wsp><wps:spPr>{props}</wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
    )
}

#[test]
fn draws_shapes_behind_and_in_front_of_the_text() {
    let red = floating_shape(
        true,
        r#"<a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>"#,
    );
    let blue = floating_shape(
        false,
        r#"<a:prstGeom prst="ellipse"/><a:noFill/><a:ln w="25400"><a:solidFill><a:srgbClr val="0000FF"/></a:solidFill></a:ln>"#,
    );
    let body = format!(
        r"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r>{blue}{red}</w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let list = render(&docx(&body, &[], ""));
    let items = list.pages()[0].items();
    let color = |item: &Item| match item {
        Item::Path(path) => Some([path.color.r, path.color.g, path.color.b]),
        _ => None,
    };
    // The shape behind the text comes before it, and the one in front comes after it, though
    // the paragraph anchors the front one first.
    assert_eq!(
        items.first().and_then(color),
        Some([255, 0, 0]),
        "{items:?}"
    );
    assert_eq!(items.last().and_then(color), Some([0, 0, 255]), "{items:?}");
    assert!(matches!(&items[1], Item::Glyphs(run) if run.text == "Body"));
    // The rectangle fills its box.
    let Item::Path(rect) = &items[0] else {
        panic!("{items:?}");
    };
    let PathCommand::MoveTo(corner) = rect.commands[0] else {
        panic!("{rect:?}");
    };
    assert_eq!(
        (points(corner.x.units()), points(corner.y.units())),
        (100.0, 100.0)
    );
    // A shape without text does not move the text around it yet.
    let (ascent, _) = carlito_line();
    let page = &lines(&list)[0];
    assert!((page[0].0 - (36.0 + ascent)).abs() <= 0.12, "{page:?}");
}

#[test]
fn draws_a_white_fill_and_a_white_line_over_the_shape_under_them() {
    // A rectangle filled white with a white line, in front of a red one behind the text: both
    // white parts cover the red, as any other color does.
    let red = floating_shape(
        true,
        r#"<a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>"#,
    );
    let white = floating_shape(
        false,
        r#"<a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill><a:ln w="76200"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:ln>"#,
    );
    let body = format!(
        r"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r>{white}{red}</w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let list = render(&docx(&body, &[], ""));
    let colors: Vec<[u8; 3]> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Path(path) => Some([path.color.r, path.color.g, path.color.b]),
            _ => None,
        })
        .collect();
    assert_eq!(colors, [[255, 0, 0], [255; 3], [255; 3]]);
}

#[test]
fn stacks_the_drawings_of_a_layer_by_their_relative_heights() {
    // Three shapes in front of the text: the one anchored first lies on top by its
    // `relativeHeight`, and the two of the same height keep the order of their anchors.
    let shape = |color: &str, height: u32| {
        floating_shape(
            false,
            &format!(
                r#"<a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="{color}"/></a:solidFill>"#
            ),
        )
        .replacen(
            r#"behindDoc="0""#,
            &format!(r#"behindDoc="0" relativeHeight="{height}""#),
            1,
        )
    };
    let shapes = [shape("FF0000", 3), shape("00FF00", 2), shape("0000FF", 2)].concat();
    let body = format!(
        r"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r>{shapes}</w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let list = render(&docx(&body, &[], ""));
    let colors: Vec<[u8; 3]> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Path(path) => Some([path.color.r, path.color.g, path.color.b]),
            _ => None,
        })
        .collect();
    assert_eq!(colors, [[0, 255, 0], [0, 0, 255], [255, 0, 0]]);
}

#[test]
fn draws_an_inline_text_box_in_its_room_on_the_line() {
    let shape = format!(
        r#"<w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:inline><wp:extent cx="1270000" cy="635000"/><a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="rect"/><a:ln w="12700"><a:solidFill><a:srgbClr val="0000FF"/></a:solidFill></a:ln></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="0"/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing>"#
    );
    let body = format!(
        r"<w:p><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r><w:r>{shape}</w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
    );
    let list = render(&docx(&body, &[], ""));
    let glyphs = |text: &str| {
        list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                Item::Glyphs(run) if run.text == text => Some((
                    points(run.glyphs[0].x.units()),
                    points(run.glyphs[0].y.units()),
                )),
                _ => None,
            })
            .unwrap()
    };
    let (a, inside) = (glyphs("A"), glyphs("Inside"));
    let (ascent, _) = carlito_line();
    // The box stands on the baseline of its line, 50 pt high, right after the "A", and its
    // text starts at its top left corner.
    assert!(
        inside.0 > a.0 + 3.0 && inside.0 < a.0 + 10.0,
        "{a:?} {inside:?}"
    );
    // The text starts below half the 1 pt outline. The box's top is off the 0.24 pt grid, so
    // the text's baseline moves to a grid step.
    assert!(
        (inside.1 - (a.1 - 50.0 + 0.5 + ascent)).abs() <= 0.24,
        "{a:?} {inside:?} {ascent}"
    );
    // Its line is drawn in blue.
    let blue = list.pages()[0]
        .items()
        .iter()
        .any(|item| matches!(item, Item::Path(p) if (p.color.r, p.color.b) == (0, 255)));
    assert!(blue);
}

#[test]
fn puts_a_line_of_one_inline_object_in_the_first_free_piece_that_holds_it_or_below_the_drawing() {
    // A text box of 80 by 60 pt with square wrap, 60 pt right of the left margin of a column
    // of 228 pt, leaves a free piece of 60 pt on its left and of 88 pt on its right.
    let place = anchored_at("margin", 762_000, 0);
    let drawing = text_box(&format!(
        r#"{place}<wp:extent cx="1016000" cy="762000"/><wp:wrapSquare/>"#
    ));
    // The next paragraph holds only an inline text box `width` EMU wide and 20 pt tall.
    let at = |width: u32| {
        let inline = format!(
            r#"<w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:inline><wp:extent cx="{width}" cy="254000"/><a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="0"/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing>"#
        );
        let body = format!(
            r"<w:p>{drawing}</w:p><w:p><w:r>{inline}</w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
        );
        let page = &placed(&render(&docx(&body, &[], &compatibility_mode(15))))[0];
        let (x, y, _) = page.iter().find(|(_, _, t)| t == "Inside").unwrap();
        (*x, *y)
    };
    // An object that both pieces hold goes in the left one, and one that only the right piece
    // holds in the right one, beside the drawing.
    let (x, y) = at(635_000);
    assert!((x - 36.0).abs() <= 0.12, "{x}");
    assert!(y < 36.0 + 60.0, "{y}");
    let (x, y) = at(1_016_000);
    assert!((x - (36.0 + 140.0)).abs() <= 0.12, "{x}");
    assert!(y < 36.0 + 60.0, "{y}");
    // An object that no piece holds goes below the drawing, at the margin.
    let (x, y) = at(1_524_000);
    assert!((x - 36.0).abs() <= 0.12, "{x}");
    assert!(y > 36.0 + 60.0, "{y}");
}

#[test]
fn keeps_the_text_beside_a_text_box_that_fits_its_text_down_to_its_fitted_bottom() {
    // A text box of 80 pt across with square wrap, 60 pt right of the left margin, that fits
    // its one line of text without insets, though the file makes it 100 pt tall.
    let place = anchored_at("margin", 762_000, 0);
    let drawing = |fit: &str| {
        format!(
            r#"<w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:anchor distT="0" distB="0" distL="0" distR="0">{place}<wp:extent cx="1016000" cy="1270000"/><wp:wrapSquare/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>Box</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="0">{fit}</wps:bodyPr></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
        )
    };
    // The next paragraph holds only an inline text box 120 pt wide, which no free piece
    // beside the box holds, so that its line goes below the box.
    let inline = format!(
        r#"<w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:inline><wp:extent cx="1524000" cy="254000"/><a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>Inside</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr lIns="0" tIns="0" rIns="0" bIns="0"/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing>"#
    );
    let below = |fit: &str| {
        let body = format!(
            r"<w:p>{}</w:p><w:p><w:r>{inline}</w:r></w:p><w:sectPr>{SECTION}</w:sectPr>",
            drawing(fit)
        );
        let page = &placed(&render(&docx(&body, &[], &compatibility_mode(15))))[0];
        let (_, y, _) = page.iter().find(|(_, _, t)| t == "Inside").unwrap();
        *y
    };
    let (ascent, _) = carlito_line();
    // A box that does not fit its text keeps the text out down to its height in the file.
    let fixed = below("");
    assert!((fixed - (36.0 + 100.0 + ascent)).abs() <= 0.25, "{fixed}");
    // A box that fits its text keeps it out down to the bottom of its one line.
    let fitted = below("<a:spAutoFit/>");
    assert!(fitted < 36.0 + 30.0 + ascent, "{fitted}");
    assert!(fitted > 36.0 + 10.0 + ascent, "{fitted}");
}

#[test]
fn keeps_the_first_line_indent_beside_a_drawing_on_the_left() {
    // A text box of 60 by 60 pt at the top left corner of the margins, with square wrap, and
    // a paragraph with a first line indent of 20 pt beside it.
    let place = anchored_at("margin", 0, 0);
    let drawing = text_box(&format!(
        r#"{place}<wp:extent cx="762000" cy="762000"/><wp:wrapSquare/>"#
    ));
    let body = format!(
        r#"<w:p><w:pPr><w:ind w:firstLine="400"/></w:pPr>{drawing}<w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let page = &placed(&render(&docx(&body, &[], "")))[0];
    let (x, _, _) = page.iter().find(|(_, _, t)| t == "Body").unwrap();
    assert!((x - (36.0 + 60.0 + 20.0)).abs() <= 0.12, "{page:?}");
}

#[test]
fn starts_the_line_after_a_clearing_break_below_the_drawing() {
    // A text box of 60 by 60 pt at the top left corner of the margins, with square wrap.
    let place = anchored_at("margin", 0, 0);
    let drawing = text_box(&format!(
        r#"{place}<wp:extent cx="762000" cy="762000"/><wp:wrapSquare/>"#
    ));
    let at = |br: &str| {
        let body = format!(
            r"<w:p>{drawing}<w:r>{CARLITO_RUN}<w:t>Beside</w:t>{br}<w:t>After</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
        );
        let page = &placed(&render(&docx(&body, &[], "")))[0];
        let (x, y, _) = page.iter().find(|(_, _, t)| t == "After").unwrap();
        (*x, *y)
    };
    // After a plain break, the line stays beside the drawing. After a clearing break, it
    // starts at the margin below the drawing, which ends 60 pt below the top margin.
    let (x, _) = at("<w:br/>");
    assert!((x - 96.0).abs() <= 0.12, "{x}");
    let (x, y) = at(r#"<w:br w:type="textWrapping" w:clear="all"/>"#);
    assert!((x - 36.0).abs() <= 0.12, "{x}");
    assert!(y > 36.0 + 60.0, "{y}");
}

#[test]
fn sizes_a_text_box_by_its_share_of_the_margins() {
    // A text box at the right margin, 100 pt wide by its extent but 40% of the 228 pt between
    // the margins by its relative width, so 91.2 pt.
    let place = r#"<wp:positionH relativeFrom="margin"><wp:align>right</wp:align></wp:positionH><wp:positionV relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="635000"/><wp14:sizeRelH xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" relativeFrom="margin"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><wp:wrapNone/>"#;
    let body = format!(
        r"<w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        text_box(place)
    );
    let page = &placed(&render(&docx(&body, &[], "")))[0];
    let (x, _, _) = page.iter().find(|(_, _, t)| t == "Box").unwrap();
    // The box starts at 36 + 228 − 91.2 pt, and its text 7.2 pt further in.
    assert!((x - (36.0 + 228.0 - 91.2 + 7.2)).abs() <= 0.12, "{page:?}");
}

#[test]
fn draws_a_text_box_of_a_share_of_the_margins_inside_its_effect_extent() {
    // A text box of 40% of the 228 pt between the margins, 91.2 pt, with an effect extent of
    // 5 pt at its left: the share is the box with the extent, so the text box is 86.2 pt wide
    // and starts 5 pt inside the box that its position places.
    let place = |across: &str| {
        format!(
            r#"<wp:positionH relativeFrom="margin">{across}</wp:positionH><wp:positionV relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="635000"/><wp:effectExtent l="63500" t="0" r="0" b="0"/><wp14:sizeRelH xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" relativeFrom="margin"><wp14:pctWidth>40000</wp14:pctWidth></wp14:sizeRelH><wp:wrapNone/>"#
        )
    };
    let start = |across: &str| {
        let body = format!(
            r"<w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
            text_box(&place(across))
        );
        let page = &placed(&render(&docx(&body, &[], "")))[0];
        page.iter().find(|(_, _, t)| t == "Box").unwrap().0
    };
    // From an offset of 20 pt, the box starts at 36 + 20 pt and the text box 5 pt further in.
    let x = start("<wp:posOffset>254000</wp:posOffset>");
    assert!((x - (36.0 + 20.0 + 5.0 + 7.2)).abs() <= 0.12, "{x}");
    // At the right margin, the box ends at 36 + 228 pt, and so does the text box.
    let x = start("<wp:align>right</wp:align>");
    assert!((x - (36.0 + 228.0 - 86.2 + 7.2)).abs() <= 0.12, "{x}");
}

#[test]
fn keeps_a_wrapped_drawing_from_its_paragraph_below_the_top_margin() {
    // A red box 18 pt above the first paragraph, on a page whose top margin is 36 pt. In mode
    // 15, a box that text wraps around stops at the top margin, but one without a wrap, or one
    // in an older mode, goes up into the margin.
    let shape = |wrap: &str| {
        format!(
            r#"<w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:anchor behindDoc="0"><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>-228600</wp:posOffset></wp:positionV><wp:extent cx="635000" cy="317500"/>{wrap}<a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
        )
    };
    let top = |wrap: &str, mode: u32| {
        let body = format!(
            r"<w:p>{}<w:r><w:t>Body</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>",
            shape(wrap)
        );
        let list = render(&docx(&body, &[], &compatibility_mode(mode)));
        list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                Item::Path(path) => match path.commands[0] {
                    PathCommand::MoveTo(corner) => Some(points(corner.y.units())),
                    _ => None,
                },
                _ => None,
            })
            .unwrap()
    };
    assert!((top("<wp:wrapSquare/>", 15) - 36.0).abs() < 0.01);
    assert!((top("<wp:wrapTopAndBottom/>", 15) - 36.0).abs() < 0.01);
    assert!((top("<wp:wrapNone/>", 15) - 18.0).abs() < 0.01);
    assert!((top("<wp:wrapSquare/>", 14) - 18.0).abs() < 0.01);
}

#[test]
fn grows_a_cell_to_hold_a_drawing_that_wraps_only() {
    // A one-cell table holds a line and a text box 72 pt tall at the top of the line's
    // paragraph. "After" follows the table. The row holds the box when the box wraps text
    // (`wp:wrapSquare`), whereas `wp:wrapNone` does not grow the row even in a centered cell.
    // A box wrapped top and bottom keeps the line of "Cell" below it.
    let after = |wrap: &str, align: &str| {
        let place = format!(
            r#"<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="914400" cy="914400"/>{wrap}"#
        );
        let body = format!(
            r#"<w:tbl><w:tblGrid><w:gridCol w:w="4320"/></w:tblGrid><w:tr><w:tc><w:tcPr><w:vAlign w:val="{align}"/></w:tcPr><w:p>{}<w:r>{CARLITO_RUN}<w:t>Cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl>{}<w:sectPr>{SECTION}</w:sectPr>"#,
            text_box(&place),
            para("After")
        );
        let page = &lines(&render(&docx(&body, &[], "")))[0];
        let y = |text: &str| {
            page.iter()
                .find(|(_, t)| t.contains(text))
                .unwrap_or_else(|| panic!("{text} {page:?}"))
                .0
        };
        y("After") - y("Cell")
    };
    let (_, line) = carlito_line();
    let free = after("<wp:wrapNone/>", "top");
    assert!(free < line + 1.0, "{free}");
    let centered = after("<wp:wrapNone/>", "center");
    assert!((centered - free).abs() < 0.01, "{centered} {free}");
    // "After" starts at the box's bottom, 72 pt below the top of the line of "Cell".
    let held = after("<wp:wrapSquare/>", "top");
    assert!((held - 72.0).abs() < 0.25, "{held}");
    let below = after("<wp:wrapTopAndBottom/>", "top");
    assert!((below - free).abs() < 0.01, "{below} {free}");
}

#[test]
fn places_a_drawing_from_the_column_or_the_margin_of_its_table_cell() {
    // A table of two columns of 72 pt with cell margins of 5.4 pt, whose first cell's text
    // starts at the 36 pt margin, so that the second cell's text starts at 36 + 72 pt. A box
    // 6 pt right of the column or the margin of the second cell starts 6 pt right of that
    // cell's text, and not 6 pt right of the page's margin.
    for from in ["column", "margin"] {
        let shape = format!(
            r#"<w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:anchor behindDoc="0" layoutInCell="1"><wp:positionH relativeFrom="{from}"><wp:posOffset>76200</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="254000" cy="254000"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp><wps:spPr><a:prstGeom prst="rect"/><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
        );
        let cell =
            |content: &str| format!("<w:tc><w:p>{content}<w:r><w:t>x</w:t></w:r></w:p></w:tc>");
        let body = format!(
            r#"<w:tbl><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:tblGrid><w:gridCol w:w="1440"/><w:gridCol w:w="1440"/></w:tblGrid><w:tr>{}{}</w:tr></w:tbl><w:p/><w:sectPr>{SECTION}</w:sectPr>"#,
            cell(""),
            cell(&shape)
        );
        let list = render(&docx(&body, &[], ""));
        let left = list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                Item::Path(path) if path.color.r == 255 => match path.commands[0] {
                    PathCommand::MoveTo(corner) => Some(points(corner.x.units())),
                    _ => None,
                },
                _ => None,
            })
            .unwrap();
        assert!((left - (36.0 + 72.0 + 6.0)).abs() < 0.01, "{from} {left}");
    }
}