f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
//! Pictures in inline drawings (`pic:pic`): the image part that they show and where the image
//! lies in the drawing's box.

use std::num::NonZeroU16;

use f_office_drawingml::Feature;
use f_office_drawingml::color::percentage;
use f_office_drawingml::effect::{Glow, OuterShadow, Reflection, picture_effects};
use f_office_drawingml::shape::{
    Geometry, PictureLine, picture_clip_path, picture_properties, turned_clockwise,
};
use f_office_paint::{
    Clip, FillRule, Image, ImageColor, ImageFormat, ImageItem, Item, Opacity, PathCommand, Point,
    Turn,
};
use f_office_units::scale::DRAWING_WHOLE;
use f_office_units::{Edges, Length, div_round_i128, saturated};
use f_office_warnings::Name;
use f_office_xml::NodeId;

use crate::body::{Block, DrawingMut, visit_drawings};
use crate::ns::{A, O, PIC, R};
use crate::reader::PartReader;
use crate::warnings::{Drawing, Reason};

mod natural;

pub(crate) use natural::{bullet_natural_size, scale_to_original};

/// A picture of an inline drawing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Picture {
    /// The relationship ID of the image part (`a:blip r:embed`).
    pub embed: String,
    /// The image, once the relationships of the part that holds the picture resolve `embed`.
    pub image: Option<Image>,
    /// The picture's alpha multiplier (`a:alphaModFix`).
    pub opacity: Opacity,
    /// Color effects applied to decoded pixels (`a:grayscl`, `a:lum`, `a:biLevel`, `a:duotone`,
    /// `a:clrChange`).
    pub color: ImageColor,
    /// The distance from the left edge of the drawing's box to the picture.
    pub left: Length,
    /// The distance from the top edge of the drawing's box to the picture.
    pub top: Length,
    /// The width of the picture.
    pub width: Length,
    /// The height of the picture.
    pub height: Length,
    /// The parts of the image that are cut off at its edges, in thousandths of a percent of
    /// the image (`a:srcRect`). A negative value adds space.
    pub crop: Edges<i64>,
    /// How the picture is turned about the centre of its frame: flipped (`flipH`, `flipV`)
    /// and then rotated clockwise by whole quarter turns (`rot`), or `None` when it is upright.
    pub turn: Option<Turn>,
    /// Whether the picture is a VML one in its text line, which stands lower on a line of
    /// multiple spacing that holds no text.
    pub drops: bool,
    /// The line around the picture (`a:ln` of `pic:spPr`) that F-Office can draw.
    pub line: Option<Box<PictureLine>>,
    /// The picture's own outer shadow (`a:outerShdw` of `pic:spPr`) that a layout can draw.
    pub shadow: Option<Box<PictureShadow>>,
    /// The picture's soft-edge effect (`a:softEdge` of `pic:spPr`) when its radius is above zero.
    pub soft_edge: Option<Box<PictureSoftEdge>>,
    /// The picture's own glow (`a:glow` of `pic:spPr`) that a layout can draw.
    pub glow: Option<Box<PictureGlow>>,
    /// The picture's own reflection (`a:reflection` of `pic:spPr`) that a layout can draw.
    pub reflection: Option<Box<PictureReflection>>,
    /// The outline geometry of the picture (`Geometry::Rect` by default).
    pub geometry: Geometry,
    /// The steps of a whole in which an inline VML picture scales its image's natural size to
    /// its size once the image is attached, as the reader's VML sizes decide, or `None` when
    /// it keeps its size, as every other picture does.
    pub scale_steps: Option<NonZeroU16>,
    /// Whether the picture took a scaled size, as an inline VML picture or a preview does from
    /// its image's natural size or its object's original size. The image of such a picture
    /// lies on the device's dots when it is a raster image of a measured format
    /// ([`Self::lies_on_device_dots`]).
    pub on_device_dots: bool,
}

/// The outer shadow of a picture, with the part that holds the picture, which a layout that
/// does not draw the shadow names in its warning.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureShadow {
    /// The shadow.
    pub shadow: OuterShadow,
    /// The part that holds the picture.
    pub part: Name,
}

/// The soft edge of a picture (`a:softEdge`), with the part that holds the picture, which a
/// layout that cannot draw it names in its warning.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureSoftEdge {
    /// The soft-edge radius (`rad`), above zero.
    pub radius: Length,
    /// The part that holds the picture.
    pub part: Name,
}

/// The glow of a picture (`a:glow`), with the part that holds the picture, which a layout that
/// does not draw the glow names in its warning.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureGlow {
    /// The glow.
    pub glow: Glow,
    /// The part that holds the picture.
    pub part: Name,
}

/// The reflection of a picture (`a:reflection`), with the part that holds the picture, which a
/// layout that does not draw the reflection names in its warning.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureReflection {
    /// The reflection.
    pub reflection: Reflection,
    /// The part that holds the picture.
    pub part: Name,
}

/// A picture's size scaled, with its aspect kept, to fit inside the size cut to whole twips:
/// the side that loses the larger share to the cut keeps its whole twips, and the other
/// shrinks with it.
///
/// The products take the part of a side that the cut removes, less than a twip, in place of
/// the cut side: `cut_w * h <= cut_h * w` is `rest_h * w <= rest_w * h`, and the other side is
/// `h + div_round(-(h * rest_w), w)`, which equals `div_round(h * cut_w, w)`, so that they fit
/// for every size within [`Length::FILE_LIMIT`].
#[must_use]
pub fn fit_to_twips(width: Length, height: Length) -> (Length, Length) {
    let twip = Length::UNITS_PER_TWIP;
    let (w, h) = (width.units(), height.units());
    if w <= 0 || h <= 0 {
        return (width, height);
    }
    let (rest_w, rest_h) = (w % twip, h % twip);
    if rest_h * w <= rest_w * h {
        (
            Length::from_units(w - rest_w),
            Length::from_units(h + f_office_units::div_round(-(h * rest_w), w)),
        )
    } else {
        (
            Length::from_units(w + f_office_units::div_round(-(w * rest_h), h)),
            Length::from_units(h - rest_h),
        )
    }
}

/// A picture's drawn aspect `(aspect_w, aspect_h)` fitted inside `(width, height)` cut down to
/// whole twips: the side that meets the cut frame keeps its whole twips, and the other shrinks
/// proportionally. Falls back to [`fit_to_twips`] when any side is not above zero.
#[must_use]
pub(crate) fn fit_aspect_to_twips(
    (width, height): (Length, Length),
    (aspect_w, aspect_h): (Length, Length),
) -> (Length, Length) {
    let twip = Length::UNITS_PER_TWIP;
    let (wc, hc) = (
        width.units() - width.units().rem_euclid(twip),
        height.units() - height.units().rem_euclid(twip),
    );
    let (aw, ah) = (aspect_w.units(), aspect_h.units());
    if wc <= 0 || hc <= 0 || aw <= 0 || ah <= 0 {
        return fit_to_twips(width, height);
    }
    let (wc, hc, aw, ah) = (
        i128::from(wc),
        i128::from(hc),
        i128::from(aw),
        i128::from(ah),
    );
    if wc * ah <= hc * aw {
        (
            Length::from_units(saturated(wc)),
            Length::from_units(saturated(div_round_i128(wc * ah, aw))),
        )
    } else {
        (
            Length::from_units(saturated(div_round_i128(hc * aw, ah))),
            Length::from_units(saturated(hc)),
        )
    }
}

/// The drawn extent (`pic:spPr/a:xfrm/a:ext`) of `pic`, when both `cx` and `cy` read as
/// positive lengths.
fn drawn_extent(doc: &f_office_xml::Document, pic: NodeId) -> Option<(Length, Length)> {
    let ext = doc
        .child(pic, PIC, "spPr")
        .and_then(|shape| doc.child(shape, A, "xfrm"))
        .and_then(|xfrm| doc.child(xfrm, A, "ext"))?;
    let cx = doc
        .attribute(ext, None, "cx")
        .and_then(f_office_drawingml::emu_length)?;
    let cy = doc
        .attribute(ext, None, "cy")
        .and_then(f_office_drawingml::emu_length)?;
    (cx > Length::ZERO && cy > Length::ZERO).then_some((cx, cy))
}

impl Picture {
    /// Reads the picture of an inline drawing (`wp:inline`) whose picture lies in `frame`, its
    /// box in the drawing's box. A drawing that holds no picture, a picture without an embedded
    /// image, and a picture rotated by an angle other than whole quarter turns give `None`.
    ///
    /// The picture takes its frame's size (or, under `PictureAspect::DrawnExtent`, its drawn
    /// extent's aspect) scaled to fit inside the frame cut to whole twips, as Word draws it.
    pub(crate) fn read(
        reader: &mut PartReader,
        inline: NodeId,
        frame: Edges<Length>,
    ) -> Option<Self> {
        let doc = reader.doc;
        let pic = doc
            .child(inline, A, "graphic")
            .and_then(|graphic| doc.child(graphic, A, "graphicData"))
            .and_then(|data| doc.child(data, PIC, "pic"))?;
        let (width, height) = reader
            .turned_pictures()
            .fit_size((frame.width(), frame.height()), drawn_extent(doc, pic));
        let fitted = Edges::placed(frame.left, frame.top, width, height)?;
        Self::from_pic(reader, pic, fitted)
    }

    /// Reads a picture (`pic:pic`) that lies in `frame`, its box in the drawing's box, as
    /// [`Picture::read`] does.
    pub(crate) fn from_pic(
        reader: &mut PartReader,
        pic: NodeId,
        frame: Edges<Length>,
    ) -> Option<Self> {
        let doc = reader.doc;
        let fill = doc.child(pic, PIC, "blipFill")?;
        let blip = doc.child(fill, A, "blip")?;
        let embed = embedded_image(reader, blip, BLIP_IMAGE)?;
        let turn = match turn_of(reader, pic) {
            Shape::Upright => None,
            Shape::Turned(turn) => Some(turn),
            Shape::OtherAngle => return None,
        };
        // The picture is drawn in its box in its own colors, with its line and its shadow,
        // without what F-Office does not draw, each with a warning.
        let look = doc
            .child(pic, PIC, "spPr")
            .map_or_default(|props| picture_properties(doc, props, reader.drawing_warnings()));
        let shadow = look.shadow.map(|shadow| {
            Box::new(PictureShadow {
                shadow,
                part: Name::new(reader.part()),
            })
        });
        let soft_edge = look.soft_edge.map(|radius| {
            Box::new(PictureSoftEdge {
                radius,
                part: Name::new(reader.part()),
            })
        });
        let glow = look.glow.map(|glow| {
            Box::new(PictureGlow {
                glow,
                part: Name::new(reader.part()),
            })
        });
        let reflection = look.reflection.map(|reflection| {
            Box::new(PictureReflection {
                reflection,
                part: Name::new(reader.part()),
            })
        });
        let color = read_picture_color(reader, blip);
        let crop = shares(reader, doc.child(fill, A, "srcRect"));
        // The clip of a cropped picture is upright on the page, which shows a frame turned by
        // whole quarter turns only: a cropped picture turned by another angle is left out.
        if crop != Edges::default() && turn.is_some_and(|turn| !by_quarters(turn)) {
            reader.drawingml_feature_not_supported(Feature::Turn);
            return None;
        }
        Some(Self {
            turn,
            line: look.line.map(Box::new),
            shadow,
            soft_edge,
            glow,
            reflection,
            geometry: look.geometry,
            opacity: opacity(reader, blip),
            color,
            ..Self::new(embed, frame, crop)
        })
    }

    /// Composes an outer axis-aligned orthogonal group transform `matrix` (entries in `-1..=1`)
    /// on the left of this picture's own `turn`.
    pub(crate) fn compose_outer_turn(&mut self, matrix: [[i32; 2]; 2]) {
        if matrix == [[1, 0], [0, 1]] {
            return;
        }
        let identity = Turn {
            xx: Turn::SCALE,
            yx: 0,
            xy: 0,
            yy: Turn::SCALE,
        };
        let cur = self.turn.unwrap_or(identity);
        let next = Turn {
            xx: matrix[0][0] * cur.xx + matrix[0][1] * cur.yx,
            yx: matrix[1][0] * cur.xx + matrix[1][1] * cur.yx,
            xy: matrix[0][0] * cur.xy + matrix[0][1] * cur.yy,
            yy: matrix[1][0] * cur.xy + matrix[1][1] * cur.yy,
        };
        self.turn = (next != identity).then_some(next);
    }

    /// Composes an outer clockwise rotation `rotation` (in 60,000ths of a degree) on the left of
    /// this picture's own `turn`. Returns `false` when the picture is cropped and the resulting
    /// turn is not a whole quarter turn (or overflows).
    pub(crate) fn compose_outer_rotation(&mut self, rotation: i64) -> bool {
        let Some(outer) = any_turn(rotation, [false, false]) else {
            return false;
        };
        let identity = Turn {
            xx: Turn::SCALE,
            yx: 0,
            xy: 0,
            yy: Turn::SCALE,
        };
        let cur = self.turn.unwrap_or(identity);
        let entry = |a: i32, b: i32, c: i32, d: i32| {
            i32::try_from(f_office_units::div_round(
                i64::from(a) * i64::from(b) + i64::from(c) * i64::from(d),
                i64::from(Turn::SCALE),
            ))
            .ok()
        };
        let (Some(xx), Some(yx), Some(xy), Some(yy)) = (
            entry(outer.xx, cur.xx, outer.xy, cur.yx),
            entry(outer.yx, cur.xx, outer.yy, cur.yx),
            entry(outer.xx, cur.xy, outer.xy, cur.yy),
            entry(outer.yx, cur.xy, outer.yy, cur.yy),
        ) else {
            return false;
        };
        let next = Turn { xx, yx, xy, yy };
        if self.crop != Edges::default() && !by_quarters(next) {
            return false;
        }
        self.turn = (next != identity).then_some(next);
        true
    }

    /// A picture of the image part `embed` in `frame`, the box of the picture in its drawing's
    /// box, with the parts `crop` of the image cut off: opaque, in its colors, upright, and
    /// with no image until the relationships resolve `embed`.
    pub(crate) fn new(embed: &str, frame: Edges<Length>, crop: Edges<i64>) -> Self {
        Self {
            embed: embed.to_owned(),
            image: None,
            opacity: Opacity::FULL,
            color: ImageColor::Original,
            left: frame.left,
            top: frame.top,
            width: frame.width(),
            height: frame.height(),
            crop,
            turn: None,
            drops: false,
            line: None,
            shadow: None,
            soft_edge: None,
            glow: None,
            reflection: None,
            geometry: Geometry::Rect,
            scale_steps: None,
            on_device_dots: false,
        }
    }

    /// The picture with the alpha (`a:alphaModFix`) and color effects of its `a:blip`.
    fn with_blip(self, reader: &mut PartReader, blip: NodeId) -> Self {
        Self {
            opacity: opacity(reader, blip),
            color: read_picture_color(reader, blip),
            ..self
        }
    }

    /// Reads the picture fill (`a:blipFill`) of a shape whose box is `width` by `height`. The
    /// image, cut by its crop (`a:srcRect`), stretches over the fill rectangle (`a:stretch` with
    /// `a:fillRect`), whose insets from the box's edges are shares of the box, negative outside
    /// it. The part of the fill rectangle outside the box is cut off, as a further crop of the
    /// image. A fill without an embedded image, or a fill rectangle of no size, gives `None`.
    pub fn from_fill(
        reader: &mut PartReader,
        fill: NodeId,
        (width, height): (Length, Length),
    ) -> Option<Self> {
        let doc = reader.doc;
        let blip = doc.child(fill, A, "blip")?;
        let embed = doc.attribute(blip, Some(R), "embed")?;
        let crop = shares(reader, doc.child(fill, A, "srcRect"));
        let insets = shares(
            reader,
            doc.child(fill, A, "stretch")
                .and_then(|stretch| doc.child(stretch, A, "fillRect")),
        );
        let (left, width, crop_left, crop_right) =
            stretched(width, (insets.left, insets.right), (crop.left, crop.right))?;
        let (top, height, crop_top, crop_bottom) =
            stretched(height, (insets.top, insets.bottom), (crop.top, crop.bottom))?;
        let crop = Edges {
            left: crop_left,
            top: crop_top,
            right: crop_right,
            bottom: crop_bottom,
        };
        let frame = Edges::placed(left, top, width, height)?;
        Some(Self::new(embed, frame, crop).with_blip(reader, blip))
    }

    /// The image item of the picture when the drawing's box has its top left corner at `x` and
    /// `top`, or `None` without an image or with a crop that leaves nothing. A cropped image is
    /// scaled so that its part inside the crop fills the picture, and it is clipped to the
    /// picture.
    #[must_use]
    pub fn item(&self, x: Length, top: Length) -> Option<Item> {
        // quirk: PictureImage::DrawsStoredImage (src/quirks.rs)
        let mut image = self.image.clone()?;
        image.opacity = self.opacity;
        if self.color != ImageColor::Original {
            image.color = self.color.clone();
        }
        let whole = self.whole(x, top)?;
        let (mut image_x, mut image_y) = (whole.left, whole.top);
        let (image_width, image_height) = (whole.width(), whole.height());
        let mut frame = self.shown(x, top)?;
        // A picture turns about the centre of its frame. The image item turns about the
        // centre of the whole image, which a crop moves off the frame's centre, so the whole
        // image goes to where its centre lands, and the frame that clips it turns with it.
        if let Some(turn) = self.turn {
            // Centres in half units, which keep them whole.
            let centre = |edges: Edges<Length>| {
                Some((
                    edges.left.checked_mul(2)?.checked_add(edges.width())?,
                    edges.top.checked_mul(2)?.checked_add(edges.height())?,
                ))
            };
            let (frame_x, frame_y) = centre(frame)?;
            let (whole_x, whole_y) = centre(whole)?;
            let offset = (whole_x - frame_x, whole_y - frame_y);
            let (moved_x, moved_y) = turned_about((frame_x, frame_y), offset, turn)?;
            image_x = (moved_x - image_width).div_round(2);
            image_y = (moved_y - image_height).div_round(2);
            // A quarter turn either way stands the frame on end about its centre. A cropped
            // picture turned by another angle is left out by its reader.
            if turn.xx == 0 {
                let (width, height) = (frame.width(), frame.height());
                frame = Edges::placed(
                    (frame_x - height).div_round(2),
                    (frame_y - width).div_round(2),
                    height,
                    width,
                )?;
            }
        }
        let clip = (self.crop != Edges::default()).then_some(Clip {
            x: frame.left,
            y: frame.top,
            width: frame.width(),
            height: frame.height(),
        });
        Some(Item::Image(ImageItem {
            x: image_x,
            y: image_y,
            width: image_width,
            height: image_height,
            clip,
            turn: self.turn,
            image,
        }))
    }

    /// The box that the picture shows, inside its crop, before a turn, when the drawing's box
    /// has its top left corner at `x` and `top`; `None` when an edge lies beyond the range of
    /// a length.
    #[must_use]
    pub fn shown(&self, x: Length, top: Length) -> Option<Edges<Length>> {
        Edges::placed(
            x.checked_add(self.left)?,
            top.checked_add(self.top)?,
            self.width,
            self.height,
        )
    }

    /// The box that the picture covers on the page when the drawing's box has its top left
    /// corner at `x` and `top`: the box that it shows, stood on end about its centre by a
    /// quarter turn either way. `None` when an edge lies beyond the range of a length.
    #[must_use]
    pub fn covered(&self, x: Length, top: Length) -> Option<Edges<Length>> {
        let shown = self.shown(x, top)?;
        if self.turn.is_none_or(|turn| turn.xx != 0) {
            return Some(shown);
        }
        let (width, height) = (shown.width(), shown.height());
        // The centre in half units, which keeps it whole.
        let centre_x = shown.left.checked_mul(2)?.checked_add(width)?;
        let centre_y = shown.top.checked_mul(2)?.checked_add(height)?;
        Edges::placed(
            (centre_x - height).div_round(2),
            (centre_y - width).div_round(2),
            height,
            width,
        )
    }

    /// The box on the page that the picture's drawing covers when the drawing's box has its top
    /// left corner at `x` and `top`: the box that it covers ([`Self::covered`]), or for a
    /// picture rotated by an angle other than whole quarter turns, the box of its frame turned
    /// about its centre. `None` when an edge lies beyond the range of a length.
    #[must_use]
    pub fn drawn_bounds(&self, x: Length, top: Length) -> Option<Edges<Length>> {
        let Some(turn) = self.turn.filter(|turn| !by_quarters(*turn)) else {
            return self.covered(x, top);
        };
        let shown = self.shown(x, top)?;
        let (width, height) = (shown.width(), shown.height());
        // Half of the turned frame's extent along an axis, whose row of the turn is `row`.
        let half = |[across, down]: [i32; 2]| {
            let sum = i128::from(width.units()) * i128::from(across.unsigned_abs())
                + i128::from(height.units()) * i128::from(down.unsigned_abs());
            let half = f_office_units::div_round_i128(sum, 2 * i128::from(Turn::SCALE));
            i64::try_from(half).ok().map(Length::from_units)
        };
        let (half_width, half_height) = (half([turn.xx, turn.xy])?, half([turn.yx, turn.yy])?);
        // The centre in half units, which keeps it whole.
        let centre_x = shown.left.checked_mul(2)?.checked_add(width)?;
        let centre_y = shown.top.checked_mul(2)?.checked_add(height)?;
        Edges::placed(
            (centre_x - half_width.checked_mul(2)?).div_round(2),
            (centre_y - half_height.checked_mul(2)?).div_round(2),
            half_width.checked_mul(2)?,
            half_height.checked_mul(2)?,
        )
    }

    /// The line `line` drawn around the box that the picture covers when the drawing's box has
    /// its top left corner at `x` and `top`, turned with the picture about its frame's centre
    /// when the picture is rotated by an angle other than whole quarter turns, whose box
    /// [`Self::covered`] gives upright; any other line as it is. `None` when a point lands
    /// beyond the range of a length.
    #[must_use]
    pub fn turned_line(&self, x: Length, top: Length, mut line: Item) -> Option<Item> {
        let Some(turn) = self.turn.filter(|turn| !by_quarters(*turn)) else {
            return Some(line);
        };
        let shown = self.shown(x, top)?;
        // The centre in half units, which keeps it whole.
        let centre_x = shown.left.checked_mul(2)?.checked_add(shown.width())?;
        let centre_y = shown.top.checked_mul(2)?.checked_add(shown.height())?;
        if let Item::Path(path) = &mut line {
            for point in path.commands.iter_mut().flat_map(PathCommand::points_mut) {
                *point = turned_point(*point, (centre_x, centre_y), turn)?;
            }
        }
        Some(line)
    }

    /// Turns every point of `commands` by `self.turn` about the centre of `self.shown(x, top)`.
    pub(crate) fn turn_commands(
        &self,
        x: Length,
        top: Length,
        commands: &mut [PathCommand],
    ) -> Option<()> {
        let Some(turn) = self.turn else {
            return Some(());
        };
        let shown = self.shown(x, top)?;
        let centre_x = shown.left.checked_mul(2)?.checked_add(shown.width())?;
        let centre_y = shown.top.checked_mul(2)?.checked_add(shown.height())?;
        for point in commands.iter_mut().flat_map(PathCommand::points_mut) {
            *point = turned_point(*point, (centre_x, centre_y), turn)?;
        }
        Some(())
    }

    /// The closed vector clip path of a shaped picture (`RoundRect`, `Ellipse`, or `Custom`)
    /// placed on the page and turned with the picture, or `None` for a rectangular picture.
    pub(crate) fn clip_path(&self, x: Length, top: Length) -> Option<(Vec<PathCommand>, FillRule)> {
        let (mut commands, rule) = picture_clip_path(&self.geometry, self.shown(x, top)?)?;
        self.turn_commands(x, top, &mut commands)?;
        Some((commands, rule))
    }

    /// Whether the picture's image lies on the device's dots: the picture took a scaled size
    /// (`on_device_dots`) and its image is a PNG or JPEG file. Its bottom then stands on its
    /// line's baseline on the device, its width and height are in whole dots, and each edge
    /// then in the nearest twip. A metafile picture keeps its exact room.
    #[must_use]
    pub fn lies_on_device_dots(&self) -> bool {
        self.on_device_dots
            && self
                .image
                .as_ref()
                .is_some_and(|image| matches!(image.format, ImageFormat::Png | ImageFormat::Jpeg))
    }

    /// The box of the whole image, before its crop, when the drawing's box has its top left
    /// corner at `x` and `top`. A crop that leaves nothing, or a box whose edge lies beyond the
    /// range of a length, gives `None`.
    #[must_use]
    pub fn whole(&self, x: Length, top: Length) -> Option<Edges<Length>> {
        let left = x.checked_add(self.left)?;
        let top = top.checked_add(self.top)?;
        let crop = self.crop;
        let (image_x, width) = uncrop(left, self.width, (crop.left, crop.right))?;
        let (image_y, height) = uncrop(top, self.height, (crop.top, crop.bottom))?;
        Edges::placed(image_x, image_y, width, height)
    }

    /// The top-left, top-right, and bottom-left corners of the whole uncropped image after the
    /// picture's turn about its frame's centre, when the drawing's box has its top left corner
    /// at `x` and `top`.
    pub(crate) fn turned_whole_corners(&self, x: Length, top: Length) -> Option<[Point; 3]> {
        let shown = self.shown(x, top)?;
        let whole = self.whole(x, top)?;
        let corners = [
            Point {
                x: whole.left,
                y: whole.top,
            },
            Point {
                x: whole.right,
                y: whole.top,
            },
            Point {
                x: whole.left,
                y: whole.bottom,
            },
        ];
        let Some(turn) = self.turn else {
            return Some(corners);
        };
        let centre = (
            shown.left.checked_mul(2)?.checked_add(shown.width())?,
            shown.top.checked_mul(2)?.checked_add(shown.height())?,
        );
        Some([
            turned_point(corners[0], centre, turn)?,
            turned_point(corners[1], centre, turn)?,
            turned_point(corners[2], centre, turn)?,
        ])
    }
}

/// ISO/IEC 29500-1 20.1.8.6: each fixed alpha modifier scales the picture's alpha.
/// The modifier is limited to one whole before multiplication, including for RGBA files. An
/// amount that does not read counts as missing, with a warning, and changes nothing.
fn opacity(reader: &mut PartReader, blip: NodeId) -> Opacity {
    let doc = reader.doc;
    doc.children(blip)
        .iter()
        .copied()
        .filter(|&node| doc.is(node, A, "alphaModFix"))
        .filter_map(|node| reader.or_missing_in(node, (None, "amt"), percentage))
        .fold(Opacity::FULL, |alpha, amount| {
            alpha.times(Opacity::clamped(amount))
        })
}

/// Reads and resolves the color effects of `blip` (`a:grayscl`, `a:lum`, `a:biLevel`, `a:duotone`,
/// `a:clrChange`), warning once on [`Feature::PictureEffect`] if any effect is unsupported or
/// references a theme color absent from the document's scheme.
fn read_picture_color(reader: &mut PartReader, blip: NodeId) -> ImageColor {
    let parsed = picture_effects(reader.doc, blip, reader.drawing_warnings());
    let mut resolved = Vec::with_capacity(parsed.len());
    let mut unresolved = false;
    for effect in &parsed {
        match effect.resolve(reader.scheme()) {
            Some(color_effect) => resolved.push(color_effect),
            None => unresolved = true,
        }
    }
    if unresolved {
        reader.drawingml_feature_not_supported(Feature::PictureEffect);
    }
    ImageColor::from_effects(resolved)
}

/// The start and length of the whole image along one side, when the part between the two crops
/// fills `length` from `start`. The crops are shares that the file gives without a bound, so
/// their products are checked.
fn uncrop(start: Length, length: Length, (before, after): (i64, i64)) -> Option<(Length, Length)> {
    let shown = DRAWING_WHOLE.checked_sub(before)?.checked_sub(after)?;
    if shown <= 0 {
        return None;
    }
    let whole = length.checked_mul(DRAWING_WHOLE)?.div_round(shown);
    let cut = whole.checked_mul(before)?.div_round(DRAWING_WHOLE);
    Some((start.checked_sub(cut)?, whole))
}

/// The attributes by which an image element names its image: the relationship ID of the image
/// part that it embeds, and the attribute that links an image file outside the package in
/// place of one, as a namespace and a name.
pub(crate) type ImageAttributes = (&'static str, (&'static str, &'static str));

/// The attributes of a DrawingML image (`a:blip`): `r:embed`, and `r:link` (ECMA-376 Part 1,
/// 20.1.8.13).
pub(crate) const BLIP_IMAGE: ImageAttributes = ("embed", (R, "link"));

/// The attributes of a VML image (`v:imagedata`): `r:id`, and `o:href` (ECMA-376 Part 4,
/// 14.1.2.11).
pub(crate) const VML_IMAGE: ImageAttributes = ("id", (O, "href"));

/// The relationship ID of the image part that the image element `node` embeds, its
/// attribute `embed` of `attributes` in the relationships namespace. An element that embeds no
/// image and links an image file outside the package gives `None` with the warning that its
/// picture is left out ([`Reason::Unlinked`]), because F-Office reads no file outside the
/// package; an element that does neither gives `None` as before.
pub(crate) fn embedded_image<'d>(
    reader: &mut PartReader<'d>,
    node: NodeId,
    (embed, (link_namespace, link)): ImageAttributes,
) -> Option<&'d str> {
    let doc = reader.doc;
    let id = doc.attribute(node, Some(R), embed);
    if id.is_none() && doc.attribute(node, Some(link_namespace), link).is_some() {
        reader.drawing_skipped(Drawing::Picture, Reason::Unlinked);
    }
    id
}

/// How a picture's shape stands in its frame.
pub(crate) enum Shape {
    /// Upright.
    Upright,
    /// Flipped and rotated, by whole quarter turns or, where the target draws them, by another
    /// angle.
    Turned(Turn),
    /// Rotated by another angle where the target leaves such a picture out.
    OtherAngle,
}

/// How the picture's shape is turned (`a:xfrm`). DrawingML flips a shape in its frame and then
/// rotates it clockwise (ECMA-376 Part 1, 20.1.7.6).
fn turn_of(reader: &mut PartReader, pic: NodeId) -> Shape {
    let doc = reader.doc;
    let Some(xfrm) = doc
        .child(pic, PIC, "spPr")
        .and_then(|shape| doc.child(shape, A, "xfrm"))
    else {
        return Shape::Upright;
    };
    let on = |name| {
        doc.attribute(xfrm, None, name)
            .is_some_and(f_office_drawingml::boolean)
    };
    let rotation = reader
        .or_missing_in(xfrm, (None, "rot"), f_office_drawingml::integer)
        .unwrap_or(0);
    let shape = reader
        .turned_pictures()
        .turn(rotation, [on("flipH"), on("flipV")]);
    if matches!(shape, Shape::OtherAngle) {
        reader.drawingml_feature_not_supported(Feature::Turn);
    }
    shape
}

/// The rotation of the picture in a drawing (`wp:inline` or `wp:anchor`), clockwise in
/// 60,000ths of a degree (`a:xfrm rot` of its `pic:spPr`), or 0 without a picture or a
/// rotation. The picture's reader warns of a value that does not read.
pub(crate) fn rotation(doc: &f_office_xml::Document, drawing: NodeId) -> i64 {
    doc.child(drawing, A, "graphic")
        .and_then(|graphic| doc.child(graphic, A, "graphicData"))
        .and_then(|data| doc.child(data, PIC, "pic"))
        .and_then(|pic| doc.child(pic, PIC, "spPr"))
        .and_then(|shape| doc.child(shape, A, "xfrm"))
        .and_then(|xfrm| doc.attribute(xfrm, None, "rot"))
        .and_then(f_office_drawingml::integer)
        .unwrap_or(0)
}

/// How a picture is turned about the centre of its frame when it is mirrored across and down
/// (`flip`) and then rotated clockwise by `rotation`, in 60,000ths of a degree, by any angle:
/// the rotation's cosine and sine in millionths, rounded with no float, so that every machine
/// computes the same turn, and moved to the length one ([`unit_millionths`]). `None` when an
/// entry lies beyond the range of a turn.
pub(crate) fn any_turn(rotation: i64, [flip_x, flip_y]: [bool; 2]) -> Option<Turn> {
    let scale = i64::from(Turn::SCALE);
    let [cos, sin] = unit_millionths(turned_clockwise([scale, 0], [0, 0], rotation)?)
        .map(|entry| i32::try_from(entry).ok());
    let (cos, sin) = (cos?, sin?);
    let mirrored = |flipped: bool| if flipped { -1 } else { 1 };
    let (across, down) = (mirrored(flip_x), mirrored(flip_y));
    Some(Turn {
        xx: cos * across,
        yx: sin * across,
        xy: -sin * down,
        yy: cos * down,
    })
}

/// The pair of millionths within one of `cos` and `sin` whose length lies nearest one million,
/// the pair itself on a tie. A reader of a PDF scales a turned image's row to the length one
/// to find its turn, and finds the same millionths again only from a pair so near one: 2 in
/// 100 of the rotations, rounded alone, lie farther.
fn unit_millionths([cos, sin]: [i64; 2]) -> [i64; 2] {
    let square = i64::from(Turn::SCALE) * i64::from(Turn::SCALE);
    let off = |[a, b]: [i64; 2]| (a * a + b * b - square).abs();
    let mut best = [cos, sin];
    for (across, down) in [
        (0, -1),
        (0, 1),
        (-1, 0),
        (1, 0),
        (-1, -1),
        (-1, 1),
        (1, -1),
        (1, 1),
    ] {
        let pair = [cos + across, sin + down];
        if off(pair) < off(best) {
            best = pair;
        }
    }
    best
}

/// Whether `turn` rotates by whole quarter turns: each entry 0 or one either way.
const fn by_quarters(turn: Turn) -> bool {
    turn.xx % Turn::SCALE == 0 && turn.yx % Turn::SCALE == 0
}

/// How a picture is turned about the centre of its frame: mirrored across and down (`flip`)
/// and then rotated clockwise by `quarters` whole quarter turns, from 0 to 3, as DrawingML
/// turns a shape (ECMA-376 Part 1, 20.1.7.6), or `None` when it stays upright.
pub(crate) fn turn(quarters: i64, [flip_x, flip_y]: [bool; 2]) -> Option<Turn> {
    // The rotation's columns, where a step right and a step down go, as [xx, yx, xy, yy].
    let [xx, yx, xy, yy] = match quarters {
        0 if !flip_x && !flip_y => return None,
        0 => [1, 0, 0, 1],
        1 => [0, 1, -1, 0],
        2 => [-1, 0, 0, -1],
        _ => [0, -1, 1, 0],
    };
    let sign = |flipped: bool| if flipped { -Turn::SCALE } else { Turn::SCALE };
    let (across, down) = (sign(flip_x), sign(flip_y));
    Some(Turn {
        xx: xx * across,
        yx: yx * across,
        xy: xy * down,
        yy: yy * down,
    })
}

/// The shares of the edges (`l`, `t`, `r`, `b`) of a rectangle such as `a:srcRect` or
/// `a:fillRect`, in thousandths of a percent, 0 where none is given, and where the value does
/// not read, with a warning.
fn shares(reader: &mut PartReader, rect: Option<NodeId>) -> Edges<i64> {
    rect.map_or_else(Edges::default, |rect| {
        Edges::from(["l", "t", "r", "b"].map(|side| {
            reader
                .or_missing_in(rect, (None, side), percentage)
                .unwrap_or(0)
        }))
    })
}

/// One axis of a stretched picture fill in a box of `length`: the fill rectangle runs from the
/// share `near` of the box to the share `far` short of its end, and the image, already cut by
/// the shares `crop` of itself at each end, stretches over it. Gives the picture's offset and
/// size inside the box, and the image's crops at each end once the parts of the fill rectangle
/// outside the box are cut off, or `None` when the fill rectangle has no size.
///
/// The shares are those of [`percentage`], in the 32-bit range. The image keeps `kept`, below
/// 2^33 in size, and the cut at an end is `kept * outside / span`, whose product reaches 2^63
/// and is taken in `i128`. The part `outside` of the fill rectangle beyond an end of the box is
/// less than its size `span`, as the rectangle reaches into the box, so the cut is no larger
/// than `kept` in size, and the crop, a share and a cut, fits an `i64`: the conversion back
/// never fails.
fn stretched(
    length: Length,
    (near, far): (i64, i64),
    (crop_near, crop_far): (i64, i64),
) -> Option<(Length, Length, i64, i64)> {
    let span = DRAWING_WHOLE - near - far;
    if span <= 0 {
        return None;
    }
    let start = near.max(0);
    let end = (DRAWING_WHOLE - far).min(DRAWING_WHOLE);
    if end <= start {
        return None;
    }
    let kept = i128::from(DRAWING_WHOLE - crop_near - crop_far);
    let crop = |crop: i64, outside: i64| {
        let cut =
            f_office_units::div_round_i128(kept * i128::from(outside.max(0)), i128::from(span));
        i64::try_from(i128::from(crop) + cut).ok()
    };
    // Both shares lie between 0 and a whole.
    let share = |value: i64| (length * value).div_round(DRAWING_WHOLE);
    Some((
        share(start),
        share(end - start),
        crop(crop_near, -near)?,
        crop(crop_far, -far)?,
    ))
}

/// Gives each picture in `blocks`, also inside tables, text boxes and groups, the image that
/// `find` returns for its relationship ID. An inline picture then takes its size and its room
/// from its image when it has `scale_steps` ([`natural::scale_to_image`]).
pub fn attach_images(blocks: &mut [Block], mut find: impl FnMut(&str) -> Option<Image>) {
    visit_drawings(blocks, &mut |drawing| match drawing {
        DrawingMut::Object { picture, room } => {
            picture.image = find(&picture.embed);
            natural::scale_to_image(picture, room);
        }
        DrawingMut::Floating(floating) => {
            if let Some(picture) = floating.picture.as_mut() {
                picture.image = find(&picture.embed);
            }
        }
    });
}

/// The step `dx` right and `dy` down turned by a row of a turn, `[across, down]`, the entries
/// in millionths that a step right and a step down give: `(dx × across + dy × down) / scale`,
/// rounded to the nearest unit. Whole quarter turns give exact steps. `None` beyond the range
/// of a length.
fn turned_step(dx: Length, dy: Length, [across, down]: [i32; 2]) -> Option<Length> {
    let sum =
        i128::from(dx.units()) * i128::from(across) + i128::from(dy.units()) * i128::from(down);
    let step = f_office_units::div_round_i128(sum, i128::from(Turn::SCALE));
    i64::try_from(step).ok().map(Length::from_units)
}

/// The place `offset` from `centre` turned by `turn` about `centre`: `centre` plus the turned
/// step of `offset` ([`turned_step`]). `None` beyond the range of a length.
fn turned_about(
    (centre_x, centre_y): (Length, Length),
    (dx, dy): (Length, Length),
    turn: Turn,
) -> Option<(Length, Length)> {
    Some((
        centre_x.checked_add(turned_step(dx, dy, [turn.xx, turn.xy])?)?,
        centre_y.checked_add(turned_step(dx, dy, [turn.yx, turn.yy])?)?,
    ))
}

/// The point `point` turned by `turn` about `centre`, which is in half units: the doubled point
/// turned about it ([`turned_about`]) and halved, to the nearest unit. `None` beyond the range
/// of a length.
fn turned_point(point: Point, centre: (Length, Length), turn: Turn) -> Option<Point> {
    let dx = point.x.checked_mul(2)?.checked_sub(centre.0)?;
    let dy = point.y.checked_mul(2)?.checked_sub(centre.1)?;
    let (x, y) = turned_about(centre, (dx, dy), turn)?;
    Some(Point {
        x: x.div_round(2),
        y: y.div_round(2),
    })
}

#[cfg(test)]
mod tests {
    use f_office_paint::{Clip, Image, ImageItem, Item, Opacity, Turn};
    use f_office_units::Length;
    use f_office_xml::{Document, Limits};

    use super::{Picture, fit_to_twips, stretched, uncrop};
    use crate::ns::{A, PIC, R, WP};
    use crate::reader::PartReader;
    use f_office_units::Edges;

    fn inline(pic: &str) -> Option<Picture> {
        let xml = format!(
            r#"<wp:inline xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:r="{R}"><a:graphic><a:graphicData>{pic}</a:graphicData></a:graphic></wp:inline>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        // Whole twips, which the size keeps.
        let [x, y, width, height] = [1, 2, 300 * 1270, 400 * 1270].map(Length::from_units);
        let frame = Edges::placed(x, y, width, height).unwrap();
        Picture::read(&mut PartReader::new(&doc), doc.root().unwrap(), frame)
    }

    #[test]
    fn reads_the_image_and_its_crop() {
        let picture = inline(
            r#"<pic:pic><pic:blipFill><a:blip r:embed="rId7"/><a:srcRect l="25000" t="-5%" r="12.5%"/></pic:blipFill><pic:spPr><a:xfrm rot="21600000"/></pic:spPr></pic:pic>"#,
        )
        .unwrap();
        assert_eq!(picture.embed, "rId7");
        assert_eq!(picture.crop, Edges::from([25_000, -5_000, 12_500, 0]));
        assert_eq!(picture.image, None);
        let units = [picture.left, picture.top, picture.width, picture.height].map(Length::units);
        assert_eq!(units, [1, 2, 300 * 1270, 400 * 1270]);
    }

    #[test]
    fn carries_direct_grayscale_to_each_picture_and_fill_use() {
        use f_office_paint::ImageColor;

        for (effects, expected) in [
            ("", ImageColor::Original),
            ("<a:grayscl/>", ImageColor::Gray709),
            ("<a:grayscl/><a:grayscl/>", ImageColor::Gray709),
            ("<a:extLst><a:grayscl/></a:extLst>", ImageColor::Original),
            ("<grayscl/>", ImageColor::Original),
        ] {
            let xml = format!(
                r#"<pic:pic><pic:blipFill><a:blip r:embed="rId1">{effects}</a:blip></pic:blipFill></pic:pic>"#
            );
            let mut picture = inline(&xml).unwrap();
            let source = Image::new(vec![0xFF, 0xD8, 0xFF]);
            picture.image = Some(source.clone());
            let Item::Image(item) = picture.item(Length::ZERO, Length::ZERO).unwrap() else {
                panic!()
            };
            assert_eq!(item.image.color, expected, "{effects}");
            assert_eq!(source.color, ImageColor::Original);
            assert!(std::sync::Arc::ptr_eq(
                source.data.inline_bytes().unwrap(),
                item.image.data.inline_bytes().unwrap()
            ));

            let xml = format!(
                r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId1">{effects}</a:blip></a:blipFill>"#
            );
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            let fill = Picture::from_fill(
                &mut PartReader::new(&doc),
                doc.root().unwrap(),
                (Length::from_units(100), Length::from_units(100)),
            )
            .unwrap();
            assert_eq!(fill.color, expected);
        }
    }

    #[test]
    fn carries_fixed_alpha_modifiers_to_pictures_and_shape_fills() {
        let cases = [
            ("", 100_000),
            (r#"<a:alphaModFix amt="10000"/>"#, 10_000),
            (r#"<a:alphaModFix amt="12.5%"/>"#, 12_500),
            (r#"<a:alphaModFix amt="0"/>"#, 0),
            (r#"<a:alphaModFix amt="150000"/>"#, 100_000),
            (r#"<a:alphaModFix amt="-1"/>"#, 0),
            (r#"<a:alphaModFix/><a:alphaModFix amt="bad"/>"#, 100_000),
            (
                r#"<a:alphaModFix amt="50000"/><a:alphaModFix amt="25000"/>"#,
                12_500,
            ),
        ];
        for (effects, expected) in cases {
            let xml = format!(
                r#"<pic:pic><pic:blipFill><a:blip r:embed="rId1">{effects}</a:blip></pic:blipFill></pic:pic>"#
            );
            let mut picture = inline(&xml).unwrap();
            let source = Image::new(vec![0xFF, 0xD8, 0xFF]);
            picture.image = Some(source.clone());
            let Item::Image(item) = picture.item(Length::ZERO, Length::ZERO).unwrap() else {
                panic!()
            };
            assert_eq!(item.image.opacity.share(), expected, "{effects}");
            assert_eq!(source.opacity, Opacity::FULL);
            assert!(std::sync::Arc::ptr_eq(
                item.image.data.inline_bytes().unwrap(),
                source.data.inline_bytes().unwrap()
            ));

            let xml = format!(
                r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId1">{effects}</a:blip></a:blipFill>"#
            );
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            let fill = Picture::from_fill(
                &mut PartReader::new(&doc),
                doc.root().unwrap(),
                (Length::from_units(100), Length::from_units(100)),
            )
            .unwrap();
            assert_eq!(fill.opacity.share(), expected, "{effects}");
        }
    }

    #[test]
    fn reads_a_crop_or_an_alpha_that_does_not_read_as_missing_with_a_warning() {
        let fill = |blip: &str, crop: &str| {
            let xml = format!(
                r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId1">{blip}</a:blip><a:srcRect {crop}/></a:blipFill>"#
            );
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            let mut reader = PartReader::new(&doc);
            let size = (Length::from_units(100), Length::from_units(100));
            let picture = Picture::from_fill(&mut reader, doc.root().unwrap(), size).unwrap();
            let invalid: Vec<String> = reader
                .invalid_values()
                .into_iter()
                .map(|(element, _, _, _)| element)
                .collect();
            (picture.crop, picture.opacity.share(), invalid)
        };
        let top = Edges::from([0, 20_000, 0, 0]);
        assert_eq!(
            fill(r#"<a:alphaModFix amt="50000"/>"#, r#"l="0" t="20000""#),
            (top, 50_000, vec![])
        );
        // The left side crops nothing and the alpha changes nothing, each with a warning.
        assert_eq!(
            fill(r#"<a:alphaModFix amt="x"/>"#, r#"l="x" t="20000""#),
            (top, 100_000, vec!["srcRect".into(), "alphaModFix".into()])
        );
    }

    #[test]
    fn stretches_a_picture_fill_over_its_fill_rectangle() {
        // A box of 100 by 200 units. Across, the fill rectangle reaches 25% past the left edge
        // and lies 10% in from the right; down, it reaches 50% past the bottom. The image,
        // cut by 20% at its top, stretches over it.
        let xml = format!(
            r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId3"/><a:srcRect t="20000"/><a:stretch><a:fillRect l="-25000" r="10000" b="-50000"/></a:stretch></a:blipFill>"#
        );
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let size = (Length::from_units(100_000), Length::from_units(200_000));
        let picture =
            Picture::from_fill(&mut PartReader::new(&doc), doc.root().unwrap(), size).unwrap();
        assert_eq!(picture.embed, "rId3");
        let frame = [picture.left, picture.top, picture.width, picture.height].map(Length::units);
        // The picture covers the box but its right 10%.
        assert_eq!(frame, [0, 0, 90_000, 200_000]);
        // The fill rectangle is 115% wide, so the 25% outside is 21,739 of 100,000 of the
        // image; it is 150% tall, so the 50% below cuts a third of the 80% kept after the crop.
        assert_eq!(picture.crop, Edges::from([21_739, 20_000, 0, 26_667]));
        let flat = format!(
            r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId3"/><a:stretch><a:fillRect l="60000" r="40000"/></a:stretch></a:blipFill>"#
        );
        let doc = Document::parse(flat.as_bytes(), &Limits::default()).unwrap();
        assert_eq!(
            Picture::from_fill(&mut PartReader::new(&doc), doc.root().unwrap(), size),
            None
        );
    }

    #[test]
    fn fits_the_size_inside_the_size_cut_to_whole_twips() {
        let emus = |cx: i64, cy: i64| {
            let (width, height) = fit_to_twips(
                Length::from_emus(cx).unwrap(),
                Length::from_emus(cy).unwrap(),
            );
            (width.units(), height.units())
        };
        let twips = |n: i64| n * Length::UNITS_PER_TWIP;
        // 2812.5 by 2970.2 twips: the width loses the larger share and keeps 2812 twips.
        assert_eq!(emus(1_785_938, 1_886_084), (twips(2812), 3_771_496));
        // 5112.7 by 4346.9 twips: the height keeps 4346 twips.
        assert_eq!(emus(3_246_536, 2_760_292), (6_491_703, twips(4346)));
        // A width of whole twips still shrinks with the height.
        assert_eq!(emus(3_324_225, 866_906), (6_647_445, twips(1365)));
        // Whole twips stay as they are.
        assert_eq!(emus(1_270_000, 635_000), (twips(2000), twips(1000)));
    }

    #[test]
    fn fits_drawn_extent_aspect_inside_whole_twip_frame() {
        let pt = |n: i64| Length::from_points(n).unwrap();
        // Equal aspect matches fit_to_twips exactly.
        let frame = (
            Length::from_emus(1_785_938).unwrap(),
            Length::from_emus(1_886_084).unwrap(),
        );
        assert_eq!(
            super::fit_aspect_to_twips(frame, frame),
            fit_to_twips(frame.0, frame.1)
        );
        // 140 x 68 pt inside 144 x 72 pt -> 144 x 69.942857 pt (1,776,549 half-EMUs).
        let (w, h) = super::fit_aspect_to_twips((pt(144), pt(72)), (pt(140), pt(68)));
        assert_eq!(w, pt(144));
        assert_eq!(h.units(), 1_776_549);
        // 148 x 76 pt inside 144 x 72 pt -> 140.210526 x 72 pt (3,561,347 half-EMUs).
        let (w, h) = super::fit_aspect_to_twips((pt(144), pt(72)), (pt(148), pt(76)));
        assert_eq!(w.units(), 3_561_347);
        assert_eq!(h, pt(72));
        // Wide and tall aspects inside 144 x 100 pt.
        assert_eq!(
            super::fit_aspect_to_twips((pt(144), pt(100)), (pt(180), pt(60))),
            (pt(144), pt(48))
        );
        assert_eq!(
            super::fit_aspect_to_twips((pt(144), pt(100)), (pt(60), pt(120))),
            (pt(50), pt(100))
        );
    }

    #[test]
    fn fits_a_size_near_the_limit_of_a_length_to_whole_twips() {
        // The products of a side and the other side cut to whole twips would reach 2^92.
        let most = Length::FILE_LIMIT;
        let (width, height) = fit_to_twips(Length::from_units(most), Length::from_units(most - 1));
        let rest = most % Length::UNITS_PER_TWIP;
        assert_eq!(
            (width.units(), height.units()),
            (most - rest, 70_368_744_177_139)
        );
    }

    #[test]
    fn crops_a_fill_stretched_with_the_extreme_shares() {
        // The shares of the 32-bit range: the product of the share that the image keeps and
        // the part outside the box passes `i64`, and the crop fits it, so that no fill is left
        // out.
        let box_size = Length::from_units(100_000);
        let (low, high) = (i64::from(i32::MIN), i64::from(i32::MAX));
        for near in [low, 0, 99_999] {
            for far in [low, 0] {
                for crop in [(low, low), (low, high), (high, low), (high, high)] {
                    assert!(
                        stretched(box_size, (near, far), crop).is_some(),
                        "{near} {far} {crop:?}"
                    );
                }
            }
        }
        // The fill reaches a whole 32-bit share past the left edge of the box, and the image
        // is cut by as much at each end before.
        let (_, _, crop_near, crop_far) = stretched(box_size, (low, 0), (low, low)).unwrap();
        assert_eq!((crop_near, crop_far), (2_147_383_653, low));
    }

    #[test]
    fn leaves_out_drawings_without_a_picture_or_turned_by_another_angle() {
        let blip = r#"<pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill>"#;
        let cases = [
            String::new(),
            "<pic:pic/>".to_owned(),
            r#"<pic:pic><pic:blipFill><a:blip r:link="rId1"/></pic:blipFill></pic:pic>"#.to_owned(),
            format!(r#"<pic:pic>{blip}<pic:spPr><a:xfrm rot="1800000"/></pic:spPr></pic:pic>"#),
        ];
        for pic in cases {
            assert_eq!(inline(&pic), None, "{pic}");
        }
        let plain = format!(r#"<pic:pic>{blip}<pic:spPr><a:xfrm flipH="0"/></pic:spPr></pic:pic>"#);
        assert_eq!(inline(&plain).unwrap().turn, None);
    }

    #[test]
    fn reads_flips_and_quarter_turns() {
        let blip = r#"<pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill>"#;
        let one = Turn::SCALE;
        let turn = |xfrm: &str| {
            inline(&format!(
                "<pic:pic>{blip}<pic:spPr><a:xfrm {xfrm}/></pic:spPr></pic:pic>"
            ))
            .unwrap()
            .turn
            .map(|t| [t.xx, t.yx, t.xy, t.yy])
        };
        assert_eq!(turn(r#"flipH="1""#), Some([-one, 0, 0, one]));
        assert_eq!(turn(r#"flipV="true""#), Some([one, 0, 0, -one]));
        // A quarter turn clockwise sends a step right down and a step down left.
        assert_eq!(turn(r#"rot="5400000""#), Some([0, one, -one, 0]));
        assert_eq!(turn(r#"rot="-5400000""#), Some([0, -one, one, 0]));
        // A half turn with both flips is upright again, as its matrix shows.
        assert_eq!(
            turn(r#"rot="10800000" flipH="1" flipV="1""#),
            Some([one, 0, 0, one])
        );
        assert_eq!(turn(r#"rot="21600000""#), None);
    }

    #[test]
    fn turns_a_cropped_picture_about_the_centre_of_its_frame() {
        // A frame of 300 by 100 at (0, 0), showing the left two thirds of the image, so that
        // the whole image is 450 wide.
        let mut picture = picture([0, 0, 33_333, 0]);
        let [left, top, width, height] = [0, 0, 300, 100].map(Length::from_units);
        (picture.left, picture.top, picture.width, picture.height) = (left, top, width, height);
        let one = Turn::SCALE;
        picture.turn = Some(Turn {
            xx: 0,
            yx: one,
            xy: -one,
            yy: 0,
        });
        let Some(Item::Image(item)) = picture.item(Length::ZERO, Length::ZERO) else {
            panic!("no image");
        };
        // The frame's centre is (150, 50), and the whole image's centre (225, 50) lands 75
        // below it, at (150, 125); the frame stands on end, 100 wide and 300 high.
        let units = [item.x, item.y, item.width, item.height].map(Length::units);
        assert_eq!(units, [-75, 75, 450, 100]);
        let clip = item.clip.unwrap();
        let clip = [clip.x, clip.y, clip.width, clip.height].map(Length::units);
        assert_eq!(clip, [100, -100, 100, 300]);
        assert_eq!(item.turn, picture.turn);
    }

    /// A picture with the crop `[left, top, right, bottom]`.
    fn picture(crop: [i64; 4]) -> Picture {
        let [x, y, width, height] = [10, 20, 600, 300].map(Length::from_units);
        Picture {
            image: Some(Image::new(vec![0xFF, 0xD8, 0xFF])),
            ..Picture::new(
                "rId1",
                Edges::placed(x, y, width, height).unwrap(),
                Edges::from(crop),
            )
        }
    }

    fn rect(item: &Item) -> ([i64; 4], Option<Clip>) {
        let Item::Image(ImageItem {
            x,
            y,
            width,
            height,
            clip,
            ..
        }) = item
        else {
            panic!("not an image: {item:?}");
        };
        ([x, y, width, height].map(|l| l.units()), *clip)
    }

    /// The corner of a drawing's box at (1,000, 2,000) half-EMUs.
    const CORNER: (Length, Length) = (Length::from_units(1_000), Length::from_units(2_000));

    #[test]
    fn places_the_picture_in_the_drawings_box() {
        let item = picture([0; 4]).item(CORNER.0, CORNER.1).unwrap();
        assert_eq!(rect(&item), ([1_010, 2_020, 600, 300], None));
        let mut empty = picture([0; 4]);
        empty.image = None;
        assert_eq!(empty.item(Length::ZERO, Length::ZERO), None);
    }

    #[test]
    fn scales_a_cropped_image_so_that_its_shown_part_fills_the_picture() {
        // A quarter cut off at the left and at the top: the whole image is 4/3 as large.
        let item = picture([25_000, 25_000, 0, 0])
            .item(CORNER.0, CORNER.1)
            .unwrap();
        let clip = Clip {
            x: Length::from_units(1_010),
            y: Length::from_units(2_020),
            width: Length::from_units(600),
            height: Length::from_units(300),
        };
        assert_eq!(rect(&item), ([810, 1_920, 800, 400], Some(clip)));
        let zero = Length::ZERO;
        assert_eq!(picture([60_000, 0, 40_000, 0]).item(zero, zero), None);
        let u = Length::from_units;
        assert_eq!(
            uncrop(zero, u(100), (-50_000, -50_000)),
            Some((u(25), u(50)))
        );
        assert_eq!(uncrop(zero, u(i64::MAX), (1, 0)), None);
    }

    #[test]
    fn attaches_images_inside_text_boxes() {
        use crate::body::{Block, Content, Paragraph, Run};
        let mut empty = picture([0; 4]);
        empty.image = None;
        let paragraph = |content| {
            Block::Paragraph(Paragraph {
                runs: vec![Run {
                    content: vec![content],
                    ..Run::default()
                }],
                ..Paragraph::empty()
            })
        };
        let object = Content::Object {
            width: Length::ZERO,
            height: Length::ZERO,
            picture: Some(Box::new(empty)),
            extent: Some(Length::ZERO),
        };
        let mut floating_picture = picture([0; 4]);
        floating_picture.image = None;
        let text_box = crate::floating::Floating {
            blocks: vec![paragraph(object)],
            ..crate::floating::Floating::default()
        };
        let drawn = crate::floating::Floating {
            picture: Some(floating_picture),
            ..crate::floating::Floating::default()
        };
        let mut blocks = vec![
            paragraph(Content::Floating(Box::new(text_box))),
            paragraph(Content::Floating(Box::new(drawn))),
        ];
        super::attach_images(&mut blocks, |id| {
            (id == "rId1").then(|| Image::new(vec![0xFF, 0xD8, 0xFF]))
        });
        let floating = |index: usize| {
            let Block::Paragraph(outer) = &blocks[index] else {
                panic!("no paragraph");
            };
            let Content::Floating(floating) = &outer.runs[0].content[0] else {
                panic!("no floating drawing");
            };
            floating.clone()
        };
        let picture_of_drawing = floating(1).picture.unwrap();
        assert!(picture_of_drawing.image.is_some());
        let text_box = floating(0);
        let Block::Paragraph(inner) = &text_box.blocks[0] else {
            panic!("no paragraph in the text box");
        };
        let Content::Object {
            picture: Some(picture),
            ..
        } = &inner.runs[0].content[0]
        else {
            panic!("no picture");
        };
        assert!(picture.image.is_some());
    }
}