f-office 0.2.1

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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Tests that lay out small DOCX files with inline pictures in the body and in a header.

use std::io::Cursor;

use f_office_docx::testing::{self, WordParts as _};
use f_office_paint::{ImageFormat, ImageItem, Item, Page, Painted, PictureCrop};

use super::{Document, Options};
use crate::test_fonts::{CARLITO_RUN, carlito};

const NAMESPACES: &str = r#"xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture""#;

/// Half-EMUs in a point.
const POINT: i64 = super::Length::UNITS_PER_POINT;

/// Half-EMUs in a dot of the device grid.
const DOT: i64 = super::Length::UNITS_PER_DOT;

/// A black PNG image of 4 by 4 pixels.
pub(super) fn black_png() -> Vec<u8> {
    let pixels = image::GrayImage::new(4, 4);
    let mut bytes = Cursor::new(Vec::new());
    pixels
        .write_to(&mut bytes, image::ImageFormat::Png)
        .unwrap();
    bytes.into_inner()
}

/// A paragraph that holds an inline picture of 72 by 36 points, with an effect extent of 1 pt
/// at the left, 2 pt at the top and 3 pt at the bottom, followed by an "x".
pub(super) fn picture_paragraph(id: &str, crop: &str) -> String {
    format!(
        r#"<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r><w:drawing {NAMESPACES}><wp:inline><wp:extent cx="914400" cy="457200"/><wp:effectExtent l="12700" t="25400" r="0" b="38100"/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="{id}"/>{crop}</pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r><w:r>{CARLITO_RUN}<w:t>x</w:t></w:r></w:p>"#
    )
}

/// Packs a DOCX file whose body holds a cropped picture of a GIF file under `rId1`, and whose
/// header holds a picture of a PNG file under its own `rId1`.
fn docx() -> Vec<u8> {
    docx_with(&picture_paragraph("rId1", r#"<a:srcRect l="50000"/>"#))
}

/// Packs a DOCX file as [`docx`] does, with `content` as the body before its section.
fn docx_with(content: &str) -> Vec<u8> {
    docx_with_image(content, "body.gif", b"GIF89a".to_vec())
}

/// Packs a DOCX file as [`docx_with`] does, with the file `name` as the body's image.
fn docx_with_image(content: &str, name: &str, image: Vec<u8>) -> Vec<u8> {
    let body = format!(
        r#"{content}<w:sectPr><w:headerReference w:type="default" r:id="rId2"/></w:sectPr>"#
    );
    let header = picture_paragraph("rId1", "");
    testing::docx(&body)
        .word_part("rId2", "header", "header1.xml", "hdr", &header)
        .relationship(testing::DOCUMENT, "rId1", "image", &format!("media/{name}"))
        .part(&format!("word/media/{name}"), image)
        .relationship("word/header1.xml", "rId1", "image", "media/header.png")
        .part("word/media/header.png", black_png())
        .zip()
        .unwrap()
}

/// The image items of a page, and the baselines of its glyph runs, from the top.
fn images_and_baselines(page: &Page) -> (Vec<&ImageItem>, Vec<i64>) {
    let mut images = Vec::new();
    let mut baselines = Vec::new();
    for item in page.painted() {
        match item {
            Painted::Image(image) => images.push(image),
            Painted::Glyphs(run) => baselines.extend(run.glyphs.first().map(|g| g.y.units())),
            Painted::Rect(_)
            | Painted::Path(_)
            | Painted::Gradient(_)
            | Painted::ClipStart(_)
            | Painted::ClipEnd => {}
        }
    }
    baselines.sort_unstable();
    (images, baselines)
}

#[test]
fn keeps_the_descent_of_text_below_a_tall_picture() {
    let next = format!("<w:p><w:r>{CARLITO_RUN}<w:t>y</w:t></w:r></w:p>");
    // From the picture line's baseline, at the bottom of the picture's 39 pt box, to the
    // baseline of the next line.
    let gap = |picture: String| {
        let document = Document::open(
            &docx_with(&format!("{picture}{next}")),
            &carlito(),
            &Options::base(),
        )
        .unwrap()
        .value;
        let (images, baselines) = images_and_baselines(&document.pages()[0]);
        baselines.last().unwrap() - (images[1].y.units() + 39 * POINT)
    };
    let text = gap(picture_paragraph("rId1", ""));
    let space = gap(picture_paragraph("rId1", "")
        .replace("<w:t>x</w:t>", r#"<w:t xml:space="preserve"> </w:t>"#));
    // With text beside the picture, the line keeps the text's descent below the baseline,
    // and with only a space it ends at the bottom of the picture.
    let descent = text - space;
    assert!(descent > POINT && descent < 4 * POINT, "{text} {space}");
}

#[test]
fn stands_each_picture_s_box_on_the_exact_baseline() {
    let document = Document::open(&docx(), &carlito(), &Options::base())
        .unwrap()
        .value;
    let (images, baselines) = images_and_baselines(&document.pages()[0]);
    // The box stands on the line's exact baseline, which lies within a device dot of the
    // drawn one.
    for (image, baseline) in images.iter().zip(baselines) {
        assert!((image.y.units() + 39 * POINT - baseline).abs() < DOT);
    }
}

#[test]
fn places_each_picture_inside_its_effect_extent() {
    let document = Document::open(&docx(), &carlito(), &Options::base())
        .unwrap()
        .value;
    let (images, _) = images_and_baselines(&document.pages()[0]);
    // The header comes before the body on the page.
    let [header, body] = [images[0], images[1]];
    // Each picture's own image part, by the relationships of the part that holds it.
    assert_eq!(header.image.format, ImageFormat::Png);
    assert_eq!(body.image.format, ImageFormat::Gif);
    // The line starts at the left margin of 72 pt, and the picture 1 pt further, inside the
    // effect extent. The bottom effect extent of 3 pt lies below the picture.
    let edges = |image: &ImageItem| {
        [
            image.x.units(),
            image.y.units(),
            image.width.units(),
            image.height.units(),
        ]
    };
    assert_eq!(
        edges(header),
        [73 * POINT, header.y.units(), 72 * POINT, 36 * POINT]
    );
    assert_eq!(header.clip, None);
    // Half of the body's image is cut off at the left, so the whole image is twice as wide
    // and only the picture's own rectangle shows.
    assert_eq!(
        edges(body),
        [POINT, body.y.units(), 144 * POINT, 36 * POINT]
    );
    let clip = body.clip.unwrap();
    let clip_edges = [
        clip.x.units(),
        clip.y.units(),
        clip.width.units(),
        clip.height.units(),
    ];
    assert_eq!(
        clip_edges,
        [73 * POINT, body.y.units(), 72 * POINT, 36 * POINT]
    );
}

#[test]
fn draws_pictures_as_pixels_and_into_pdf() {
    let fonts = carlito();
    let document = Document::open(&docx(), &fonts, &Options::base())
        .unwrap()
        .value;
    let pixmap = f_office_raster::render_page(&document.pages()[0], &fonts, 72)
        .unwrap()
        .value;
    let (images, _) = images_and_baselines(&document.pages()[0]);
    let header = images[0];
    let red = |x: i64, y: i64| {
        let at = (y / POINT * i64::from(pixmap.width()) + x / POINT) * 4;
        pixmap.data()[usize::try_from(at).unwrap()]
    };
    // The header's black PNG shows in its rectangle, and the GIF of the body is left out.
    let middle_y = header.y.units() + 18 * POINT;
    assert_eq!(red(header.x.units() + 36 * POINT, middle_y), 0);
    assert_eq!(red(header.x.units() - 2 * POINT, middle_y), 255);
    let body = images[1];
    assert_eq!(
        red(body.x.units() + 108 * POINT, body.y.units() + 18 * POINT),
        255
    );
    assert!(document.write_pdf(&fonts).is_ok());
}

#[test]
fn paints_pictures_in_table_cells() {
    let cell = picture_paragraph("rId1", "");
    let table = format!(
        r#"<w:tbl><w:tblGrid><w:gridCol w:w="4000"/></w:tblGrid><w:tr><w:tc>{cell}</w:tc></w:tr></w:tbl>"#
    );
    let document = Document::open(&docx_with(&table), &carlito(), &Options::base())
        .unwrap()
        .value;
    let (images, _) = images_and_baselines(&document.pages()[0]);
    let formats: Vec<ImageFormat> = images.iter().map(|image| image.image.format).collect();
    // The header's picture comes first, then the cell's.
    assert_eq!(formats, [ImageFormat::Png, ImageFormat::Gif]);
}

#[test]
fn draws_a_floating_picture_at_its_place() {
    // A picture of 20 by 10 pt, 100 pt from the left and 50 pt from the top of the page.
    let floating = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t>x</w:t></w:r><w:r><w:drawing {NAMESPACES}><wp:anchor><wp:positionH relativeFrom="page"><wp:posOffset>1270000</wp:posOffset></wp:positionH><wp:positionV relativeFrom="page"><wp:posOffset>635000</wp:posOffset></wp:positionV><wp:extent cx="254000" cy="127000"/><wp:wrapNone/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r></w:p>"#
    );
    let document = Document::open(&docx_with(&floating), &carlito(), &Options::base())
        .unwrap()
        .value;
    let (images, baselines) = images_and_baselines(&document.pages()[0]);
    let body = images
        .iter()
        .find(|image| image.image.format == ImageFormat::Gif)
        .unwrap();
    let bounds = [
        body.x.units(),
        body.y.units(),
        body.width.units(),
        body.height.units(),
    ];
    assert_eq!(bounds, [100, 50, 20, 10].map(|pt| pt * POINT));
    // The text line of the anchor paragraph stays where it would be without the picture.
    let plain = format!(r"<w:p><w:r>{CARLITO_RUN}<w:t>x</w:t></w:r></w:p>");
    let document = Document::open(&docx_with(&plain), &carlito(), &Options::base())
        .unwrap()
        .value;
    assert_eq!(baselines, images_and_baselines(&document.pages()[0]).1);
    // With top and bottom wrap at the paragraph top, the line goes below the picture and the
    // 2 pt below it.
    let wrapped = floating
        .replace(
            r#"relativeFrom="page"><wp:posOffset>635000"#,
            r#"relativeFrom="paragraph"><wp:posOffset>0"#,
        )
        .replace("<wp:anchor>", r#"<wp:anchor distT="0" distB="25400">"#)
        .replace("<wp:wrapNone/>", "<wp:wrapTopAndBottom/>");
    let document = Document::open(&docx_with(&wrapped), &carlito(), &Options::base())
        .unwrap()
        .value;
    // The first baseline is the header's, which stays.
    let moved = images_and_baselines(&document.pages()[0]).1;
    assert_eq!(moved[0], baselines[0]);
    assert_eq!(
        moved[1] - baselines[1],
        12 * POINT,
        "{moved:?} {baselines:?}"
    );
    // An effect extent below the picture, such as a shadow, keeps the text 1 pt further down,
    // within half a device dot of the 1/300 inch grid that the baseline snaps to.
    let shadowed = wrapped.replace(
        "<wp:wrapTopAndBottom/>",
        r#"<wp:effectExtent l="0" t="0" r="0" b="12700"/><wp:wrapTopAndBottom/>"#,
    );
    let document = Document::open(&docx_with(&shadowed), &carlito(), &Options::base())
        .unwrap()
        .value;
    let shadowed = images_and_baselines(&document.pages()[0]).1;
    let half_unit = DOT / 2;
    assert!(
        (shadowed[1] - moved[1] - POINT).abs() < half_unit,
        "{shadowed:?} {moved:?}"
    );
}

/// Lays out a picture of `cx` EMU by 36 pt with square wrap at the paragraph top, placed by
/// `position_h`, with `dist_r` EMU to keep free at its right, before many words. Returns the
/// picture's left, right and bottom, and the baseline, start and end of each text line.
fn square_wrapped(position_h: &str, cx: i64, dist_r: i64) -> ([i64; 3], Vec<(i64, i64, i64)>) {
    let words = "word ".repeat(120);
    let body = format!(
        r#"<w:p><w:r><w:drawing {NAMESPACES}><wp:anchor distL="0" distT="0" distR="{dist_r}" distB="0">{position_h}<wp:positionV relativeFrom="paragraph"><wp:posOffset>0</wp:posOffset></wp:positionV><wp:extent cx="{cx}" cy="457200"/><wp:wrapSquare wrapText="bothSides"/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r><w:r>{CARLITO_RUN}<w:t>{words}</w:t></w:r></w:p>"#
    );
    let document = Document::open(&docx_with(&body), &carlito(), &Options::base())
        .unwrap()
        .value;
    let page = &document.pages()[0];
    let image = page
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Image(image) if image.image.format == ImageFormat::Gif => Some(image),
            _ => None,
        })
        .unwrap();
    let left = image.x.units();
    let bounds = [
        left,
        left + image.width.units(),
        image.y.units() + 36 * POINT,
    ];
    let mut lines: Vec<(i64, i64, i64)> = page
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Glyphs(run) if run.text.starts_with("word") => {
                let first = run.glyphs.first()?;
                let end_glyph = run.glyphs.iter().rev().find(|g| g.id != 0)?;
                Some((first.y.units(), first.x.units(), end_glyph.x.units()))
            }
            _ => None,
        })
        .collect();
    lines.sort_unstable();
    (bounds, lines)
}

#[test]
fn flows_lines_beside_a_picture_on_the_right_or_below_a_wide_one() {
    let right = r#"<wp:positionH relativeFrom="margin"><wp:align>right</wp:align></wp:positionH>"#;
    let ([left, _, bottom], lines) = square_wrapped(right, 914_400, 0);
    let beside: Vec<&(i64, i64, i64)> = lines.iter().filter(|l| l.0 < bottom).collect();
    assert!(!beside.is_empty(), "{lines:?}");
    // Beside the picture, the lines end before it and start at the margin as below it.
    let margin = lines.last().unwrap().1;
    assert!(
        beside.iter().all(|l| l.2 < left && l.1 == margin),
        "{lines:?}"
    );
    // A picture as wide as the column leaves no side wide enough, so the text goes below it.
    let page =
        r#"<wp:positionH relativeFrom="margin"><wp:posOffset>0</wp:posOffset></wp:positionH>"#;
    let ([_, _, bottom], lines) = square_wrapped(page, 30 * 914_400 / 4, 0);
    assert!(lines.iter().all(|l| l.0 > bottom), "{lines:?}");
}

#[test]
fn flows_lines_beside_a_picture_with_square_wrap() {
    // A picture of 72 by 36 pt at the column edge and the paragraph top, before many words,
    // with 9 pt to keep free at its right.
    let column =
        r#"<wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH>"#;
    let ([left, _, bottom], lines) = square_wrapped(column, 914_400, 114_300);
    let starts: Vec<(i64, i64)> = lines.iter().map(|l| (l.0, l.1)).collect();
    let beside: Vec<i64> = starts
        .iter()
        .filter(|(y, _)| *y < bottom)
        .map(|s| s.1)
        .collect();
    let below: Vec<i64> = starts
        .iter()
        .filter(|(y, _)| *y > bottom + 20 * POINT)
        .map(|s| s.1)
        .collect();
    assert!(!beside.is_empty() && !below.is_empty(), "{starts:?}");
    // The lines beside start after the picture and its 9 pt distance at the right.
    assert!(
        beside
            .iter()
            .all(|x| (*x - (left + 81 * POINT)).abs() <= POINT / 4),
        "{starts:?}"
    );
    assert!(
        below.iter().all(|x| (*x - left).abs() <= POINT / 4),
        "{starts:?}"
    );
}

#[test]
fn places_a_drawing_from_the_top_border_of_its_paragraph() {
    // A picture at the top of a paragraph that has a 1 pt top border with 8 pt of space.
    let body = format!(
        r#"<w:p><w:pPr><w:pBdr><w:top w:val="single" w:sz="8" w:space="8" w:color="000000"/></w:pBdr></w:pPr><w:r><w:drawing {NAMESPACES}><wp:anchor distL="0" distT="0" distR="0" distB="0"><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="457200" cy="457200"/><wp:wrapNone/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r><w:r>{CARLITO_RUN}<w:t>x</w:t></w:r></w:p>"#
    );
    let document = Document::open(&docx_with(&body), &carlito(), &Options::base())
        .unwrap()
        .value;
    let page = &document.pages()[0];
    let picture = page
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Image(image) if image.image.format == ImageFormat::Gif => Some(image.y.units()),
            _ => None,
        })
        .unwrap();
    let border = page
        .items()
        .iter()
        .find_map(|item| match item {
            // The 1 pt border is drawn 4 device dots (0.96 pt) thick.
            Item::Rect(rect) if rect.height.units() == 4 * DOT => Some(rect.y.units()),
            _ => None,
        })
        .unwrap();
    // The picture's top is the border's top, not the text's 9 pt lower, within half a device
    // unit of the grid that the border snaps to.
    assert!((picture - border).abs() <= DOT / 2, "{picture} {border}");
}

/// An EMF file whose 1 by 1 inch frame is 100 by 100 device pixels, with a black rectangle in
/// its left half and the text "E" in Carlito, 50 pixels high, on the baseline at (10, 80).
fn emf() -> Vec<u8> {
    let le = |values: &[i32]| -> Vec<u8> { values.iter().flat_map(|v| v.to_le_bytes()).collect() };
    let record = |kind: i32, fields: Vec<u8>| -> Vec<u8> {
        let size = i32::try_from(8 + fields.len()).unwrap();
        [le(&[kind, size]), fields].concat()
    };
    let mut header = le(&[
        0,
        0,
        99,
        99,
        0,
        0,
        2540,
        2540,
        0x464D_4520,
        0x10000,
        0,
        0,
        0,
    ]);
    // A device of 1,000 pixels over 254 mm, so that the 25.4 mm frame is 100 pixels.
    header.extend(le(&[0, 0, 0, 1000, 1000, 254, 254]));
    let mut font = le(&[1, -50, 0, 0, 0, 400, 0, 0]);
    let mut face: Vec<u16> = "Carlito".encode_utf16().collect();
    face.resize(32, 0);
    font.extend(face.iter().flat_map(|unit| unit.to_le_bytes()));
    let mut text = le(&[0, 0, 0, 0, 1, 0, 0, 10, 80, 1, 76, 0, 0, 0, 0, 0, 0]);
    text.extend([u8::try_from('E').unwrap(), 0, 0, 0]);
    [
        record(1, header),
        record(37, le(&[i32::from_ne_bytes(0x8000_0004_u32.to_ne_bytes())])),
        record(37, le(&[i32::from_ne_bytes(0x8000_0008_u32.to_ne_bytes())])),
        record(43, le(&[0, 0, 50, 100])),
        record(82, font),
        record(37, le(&[1])),
        record(22, le(&[0x18])),
        record(84, text),
        record(14, le(&[0, 0, 0])),
    ]
    .concat()
}

#[test]
fn draws_an_emf_picture_from_its_records() {
    // A picture of 1 by 1 inch.
    let paragraph = format!(
        r#"<w:p><w:r><w:drawing {NAMESPACES}><wp:inline><wp:extent cx="914400" cy="914400"/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
    );
    let document = Document::open(
        &docx_with_image(&paragraph, "body.emf", emf()),
        &carlito(),
        &Options::base(),
    )
    .unwrap()
    .value;
    let page = &document.pages()[0];
    // The picture's records come in one group, which the PDF writer leaves where it is.
    let group = page.items().iter().find_map(|item| match item {
        Item::Group(group) => Some(group),
        _ => None,
    });
    let group = group.unwrap();
    let fill = group.items.iter().find_map(|item| match item {
        Item::Path(path) => Some(path),
        _ => None,
    });
    let text = group.items.iter().find_map(|item| match item {
        Item::Glyphs(run) if run.text == "E" => Some(run),
        _ => None,
    });
    let (fill, text) = (fill.unwrap(), text.unwrap());
    // The rectangle is half an inch wide, and the text 36 pt high, from the picture's left.
    let xs: Vec<i64> = fill
        .commands
        .iter()
        .filter_map(|command| match command {
            f_office_paint::PathCommand::MoveTo(p) | f_office_paint::PathCommand::LineTo(p) => {
                Some(p.x.units())
            }
            _ => None,
        })
        .collect();
    let left = *xs.iter().min().unwrap();
    assert_eq!(xs.iter().max().unwrap() - left, 36 * POINT);
    assert_eq!(text.size.units(), 36 * POINT);
    assert_eq!(text.glyphs[0].x.units() - left, POINT * 72 / 10);
    // The header's PNG picture is an image item, and the EMF picture none.
    let emf_images = page.items().iter().filter(
        |item| matches!(item, Item::Image(image) if image.image.format == ImageFormat::Emf),
    );
    assert_eq!(emf_images.count(), 0);
}

/// What an EMF picture draws shows only inside the box that the picture shows, inside its
/// crop, as Word's PDFs cut it on each target.
#[test]
fn cuts_an_emf_picture_at_its_box_inside_the_crop() {
    // The shown box is 72 by 36 pt. A crop of 25% at the left makes the whole picture 96 pt
    // wide, from 24 pt left of the box, so its rectangle, the left half, ends 24 pt inside.
    let paragraph = picture_paragraph("rId1", r#"<a:srcRect l="25000"/>"#);
    let file = docx_with_image(&paragraph, "body.emf", emf());
    let fonts = carlito();
    let xs_and_ys = |commands: &[f_office_paint::PathCommand]| -> (Vec<i64>, Vec<i64>) {
        commands
            .iter()
            .flat_map(f_office_paint::PathCommand::points)
            .map(|point| (point.x.units(), point.y.units()))
            .unzip()
    };
    for target in crate::Target::all() {
        let options = Options {
            configuration: crate::Configuration::of(target),
            ..Options::base()
        };
        let document = Document::open(&file, &fonts, &options).unwrap().value;
        let page = &document.pages()[0];
        let group = page.items().iter().find_map(|item| match item {
            Item::Group(group) => Some(group),
            _ => None,
        });
        let group = group.unwrap();
        let (xs, ys) = xs_and_ys(&group.clip.as_ref().unwrap().commands);
        let (left, right) = (*xs.iter().min().unwrap(), *xs.iter().max().unwrap());
        let (top, bottom) = (*ys.iter().min().unwrap(), *ys.iter().max().unwrap());
        assert_eq!((right - left, bottom - top), (72 * POINT, 36 * POINT));
        let filled = group.items.iter().find_map(|item| match item {
            Item::Path(path) => Some(path),
            _ => None,
        });
        let (fill_xs, _) = xs_and_ys(&filled.unwrap().commands);
        let fill_left = *fill_xs.iter().min().unwrap();
        let fill_right = *fill_xs.iter().max().unwrap();
        assert!(
            (fill_left - (left - 24 * POINT)).abs() <= 1,
            "{fill_left} {left}"
        );
        assert!(
            (fill_right - (left + 24 * POINT)).abs() <= 1,
            "{fill_right} {left}"
        );
    }
}

/// An RGB PNG image of 8 by 4 pixels whose red level is 30 times its column.
fn columns_png() -> Vec<u8> {
    let pixels = image::RgbImage::from_fn(8, 4, |x, _| {
        image::Rgb([u8::try_from(30 * x).unwrap(), 0, 0])
    });
    let mut bytes = Cursor::new(Vec::new());
    pixels
        .write_to(&mut bytes, image::ImageFormat::Png)
        .unwrap();
    bytes.into_inner()
}

#[test]
fn writes_a_cropped_picture_as_its_visible_part_where_the_writer_does() {
    // A crop of 32% at the left puts the edge 2.56 pixels into the 8 by 4 file, which a writer
    // that crops rounds to the nearest pixel, 3.
    let paragraph = picture_paragraph("rId1", r#"<a:srcRect l="32000"/>"#);
    let file = docx_with_image(&paragraph, "body.png", columns_png());
    let fonts = carlito();
    // The picture's extent is 72 by 36 pt. A writer that crops draws the 5 by 4 pixels from
    // column 3 on there with no clip; the others draw the whole file under a clip of it.
    let extent = [72 * POINT, 36 * POINT];
    let part = (false, extent, (5, 4), [90, 0, 0], [210, 0, 0]);
    let whole = (true, extent, (8, 4), [0, 0, 0], [210, 0, 0]);
    let mut kinds = Vec::new();
    for target in crate::Target::all() {
        let (shown, crop) = cropped_on(target, &file, &fonts);
        let expected = match crop {
            PictureCrop::VisiblePart | PictureCrop::VisiblePartAtScale => part,
            PictureCrop::WholeFileUnderClip => whole,
        };
        assert_eq!(shown, expected, "{target}");
        kinds.push(crop);
    }
    assert!(
        kinds.iter().any(|kind| kind.keeps_visible_part())
            && kinds.contains(&PictureCrop::WholeFileUnderClip),
        "{kinds:?}"
    );
}

#[test]
fn keeps_the_part_that_the_file_fills_where_a_crop_lies_below_zero() {
    // A crop of -25% at the right makes the frame of 72 pt a quarter wider than the file, which
    // fills 57.6 pt of it, and a crop of 25% at the bottom keeps 3 of the file's 4 rows. A
    // writer that crops keeps those 8 by 3 pixels and draws them where the file fills the
    // frame.
    let paragraph = picture_paragraph("rId1", r#"<a:srcRect r="-25000" b="25000"/>"#);
    let file = docx_with_image(&paragraph, "body.png", columns_png());
    let fonts = carlito();
    let part = (
        false,
        [288 * POINT / 5, 36 * POINT],
        (8, 3),
        [0, 0, 0],
        [210, 0, 0],
    );
    let whole = (
        true,
        [72 * POINT, 36 * POINT],
        (8, 4),
        [0, 0, 0],
        [210, 0, 0],
    );
    for target in crate::Target::all() {
        let (shown, crop) = cropped_on(target, &file, &fonts);
        let expected = match crop {
            PictureCrop::VisiblePart | PictureCrop::VisiblePartAtScale => part,
            PictureCrop::WholeFileUnderClip => whole,
        };
        assert_eq!(shown, expected, "{target}");
    }
}

/// What the second picture of the first page of `file` shows on `target`, with the crop of the
/// target's PDF writer.
fn cropped_on(target: crate::Target, file: &[u8], fonts: &crate::FontDb) -> (Shown, PictureCrop) {
    let crop = crate::suite::profile::Profile::of(target)
        .unwrap()
        .writer()
        .picture_crop();
    let options = Options {
        configuration: crate::Configuration::of(target),
        ..Options::base()
    };
    let document = Document::open(file, fonts, &options).unwrap().value;
    let (images, _) = images_and_baselines(&document.pages()[0]);
    (shown(images[1]), crop)
}

/// Whether a picture has a clip, the size of what it shows in units, its pixels, and its first
/// and last pixels.
type Shown = (bool, [i64; 2], (u32, u32), [u8; 3], [u8; 3]);

/// What a picture shows ([`Shown`]).
fn shown(picture: &ImageItem) -> Shown {
    let size = picture
        .clip
        .map_or([picture.width.units(), picture.height.units()], |clip| {
            [clip.width.units(), clip.height.units()]
        });
    let bytes = picture.image.load_bytes().unwrap();
    let pixels = png_pixels(&bytes);
    let (width, height) = pixels.dimensions();
    let first = pixels.get_pixel(0, 0).0;
    let last = pixels.get_pixel(width - 1, height - 1).0;
    (picture.clip.is_some(), size, (width, height), first, last)
}

/// The RGB pixels of a PNG file.
fn png_pixels(data: &[u8]) -> image::RgbImage {
    image::load_from_memory_with_format(data, image::ImageFormat::Png)
        .unwrap()
        .to_rgb8()
}