f-office-docx 0.2.1

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
1428
1429
1430
1431
use super::{
    ACROSS, ALIGN_ACROSS, ALIGN_DOWN, DOWN, FILL_TYPE, FLIP, LAYOUT_FLOW, POSITION,
    RELATIVE_ACROSS, RELATIVE_DOWN, WRAP_SIDE, WRAP_TYPE, read,
};
use crate::body::Content;
use crate::enumerations::assert_names;
use crate::floating::{Floating, PageArea, Position, Relative, Wrap, WrapSides};
use crate::ns::{O, R, V, W, W10};
use crate::picture::turn;
use crate::props::Align;
use crate::quirks::{VmlPictureRoom, VmlPreviewRoom, VmlTextPath};
use crate::reader::PartReader;
use crate::reader::settings::VmlSizes;
use crate::warnings::{Drawing, ReadAs, Reason};
use f_office_drawingml::shape::Geometry;
use f_office_drawingml::theme::ShapeTheme;
use f_office_paint::{Opacity, Rgb};
use f_office_units::scale::QUARTER_TURN;
use f_office_units::{Edges, Length};
use f_office_vml::css;
use f_office_xml::{Document, Limits, NodeId};

fn parse(xml: &str) -> Document {
    Document::parse(
        format!(
            r#"<w:pict xmlns:v="{V}" xmlns:o="{O}" xmlns:r="{R}" xmlns:w="{W}" xmlns:w10="{W10}">{xml}</w:pict>"#
        )
        .as_bytes(),
        &Limits::default(),
    )
    .unwrap()
}

fn points(milli: i64) -> Length {
    Length::from_units(milli * Length::UNITS_PER_POINT / 1_000)
}

/// The floating drawing that [`read`] gives for the `w:pict` `node`, or `None`.
fn read_floating(reader: &mut PartReader, node: NodeId) -> Option<Floating> {
    match read(reader, node)? {
        Content::Floating(floating) => Some(*floating),
        _ => None,
    }
}

/// The picture in its line that [`read`] gives for the `w:pict` `node`, or `None`.
fn read_inline(reader: &mut PartReader, node: NodeId) -> Option<Content> {
    read(reader, node).filter(|content| matches!(content, Content::Object { .. }))
}

/// The shape in its line that [`read`] gives for the `w:pict` `node`, or `None`.
fn read_inline_shape(reader: &mut PartReader, node: NodeId) -> Option<Content> {
    read(reader, node).filter(|content| matches!(content, Content::Drawing(_)))
}

#[test]
fn keeps_the_css_size_of_the_preview_of_an_embedded_object() {
    let shape = r#"<v:shape style="width:36pt;height:44pt"><v:imagedata r:id="rId8"/></v:shape>"#;
    let object = |ole: &str| {
        Document::parse(
            format!(
                r#"<w:object xmlns:v="{V}" xmlns:o="{O}" xmlns:r="{R}" xmlns:w="{W}">{shape}{ole}</w:object>"#
            )
            .as_bytes(),
            &Limits::default(),
        )
        .unwrap()
    };
    let room = |doc: &Document| {
        let mut reader = PartReader::new(doc)
            .with_vml_sizes(VmlSizes::with_picture(VmlPictureRoom::NaturalScale));
        match read(&mut reader, doc.root().unwrap()) {
            Some(Content::Object {
                picture: Some(picture),
                ..
            }) => picture.scale_steps,
            _ => panic!("no picture"),
        }
    };
    let thousandths = std::num::NonZeroU16::new(1_000);
    assert_eq!(room(&parse(shape)), thousandths);
    let doc = parse(shape);
    let mut reader =
        PartReader::new(&doc).with_vml_sizes(VmlSizes::with_picture(VmlPictureRoom::AsWritten));
    assert!(matches!(
        read(&mut reader, doc.root().unwrap()),
        Some(Content::Object {
            picture: Some(ref picture),
            ..
        }) if picture.scale_steps.is_none()
    ));
    assert_eq!(room(&object("")), thousandths);
    assert_eq!(room(&object(r#"<o:OLEObject r:id="rId9"/>"#)), None);
}

#[test]
fn scales_the_original_size_of_the_preview_of_an_embedded_object() {
    let object = |original: &str, style: &str, ole: &str| {
        Document::parse(
            format!(
                r#"<w:object xmlns:v="{V}" xmlns:o="{O}" xmlns:r="{R}" xmlns:w="{W}"{original}><v:shape style="width:80pt;height:20.6pt{style}"><v:imagedata r:id="rId8"/></v:shape>{ole}</w:object>"#
            )
            .as_bytes(),
            &Limits::default(),
        )
        .unwrap()
    };
    let size = |doc: &Document, preview: VmlPreviewRoom| {
        let mut reader = PartReader::new(doc).with_vml_sizes(VmlSizes::with_preview(preview));
        match read(&mut reader, doc.root().unwrap()) {
            Some(Content::Object {
                width,
                height,
                picture: Some(picture),
                ..
            }) => {
                assert_eq!((picture.width, picture.height), (width, height));
                (width, height)
            }
            _ => panic!("no picture"),
        }
    };
    let original = r#" w:dxaOrig="1600" w:dyaOrig="8000""#;
    let ole = r#"<o:OLEObject r:id="rId9"/>"#;
    let css = (points(80_000), points(20_600));
    // 412 twips of 8,000 is 0.0515, so the scale is 0.052 of 400 pt; across, 1,600 of 1,600.
    let scaled = (points(80_000), points(20_800));
    let preview = object(original, "", ole);
    assert_eq!(size(&preview, VmlPreviewRoom::OriginalScale), scaled);
    assert_eq!(size(&preview, VmlPreviewRoom::AsWritten), css);
    let without_height = object(r#" w:dxaOrig="1600""#, "", ole);
    assert_eq!(size(&without_height, VmlPreviewRoom::OriginalScale), css);
    let turned = object(original, ";rotation:90", ole);
    assert_eq!(size(&turned, VmlPreviewRoom::OriginalScale), css);
    let plain = object(original, "", "");
    assert_eq!(size(&plain, VmlPreviewRoom::OriginalScale), css);
}

#[test]
fn reads_a_picture_in_its_line_with_its_css_size() {
    let doc = parse(
        r#"<v:shape style="width:161.35pt;height:75.2pt;visibility:visible"><v:imagedata r:id="rId8"/></v:shape>"#,
    );
    let Some(Content::Object {
        width,
        height,
        picture: Some(picture),
        extent: None,
    }) = read_inline(&mut PartReader::new(&doc), doc.root().unwrap())
    else {
        panic!("no picture");
    };
    assert_eq!(width, css::length("161.35pt").unwrap());
    assert_eq!(height, Length::from_units(75 * 25_400 + 5_080));
    assert_eq!(picture.embed, "rId8");
    assert_eq!((picture.width, picture.height), (width, height));
    // On a line of multiple spacing without text, it stands lower than the baseline.
    assert!(picture.drops);
    // A picture is not a floating shape.
    assert_eq!(
        read_floating(&mut PartReader::new(&doc), doc.root().unwrap()),
        None
    );
}

#[test]
fn reads_the_crops_of_pictures_in_65536ths() {
    // 7015 of 65536 is 10,704 of 100,000; a negative crop adds space.
    let inline = parse(
        r#"<v:shape style="width:95.1pt;height:32.25pt"><v:imagedata r:id="a" cropright="7015f" croptop="0.25"/></v:shape>"#,
    );
    let Some(Content::Object {
        picture: Some(picture),
        ..
    }) = read_inline(&mut PartReader::new(&inline), inline.root().unwrap())
    else {
        panic!("no picture");
    };
    assert_eq!(picture.crop, Edges::from([0, 25_000, 10_704, 0]));
    let floating = parse(
        r#"<v:shape style="position:absolute;width:505pt;height:133pt"><v:imagedata r:id="a" cropbottom="-16693f" cropleft="4416f"/></v:shape>"#,
    );
    let picture = read_floating(&mut PartReader::new(&floating), floating.root().unwrap())
        .and_then(|f| f.picture)
        .unwrap();
    assert_eq!(picture.crop, Edges::from([6_738, 0, 0, -25_471]));
}

#[test]
fn leaves_floating_shapes_and_shapes_without_images_out_of_the_line() {
    let floating = parse(
        r#"<v:shape style="position:absolute;width:10pt;height:10pt"><v:imagedata r:id="a"/></v:shape>"#,
    );
    assert_eq!(
        read_inline(&mut PartReader::new(&floating), floating.root().unwrap()),
        None
    );
    let empty = parse(r#"<v:shape style="width:10pt;height:10pt"/>"#);
    assert_eq!(
        read_inline(&mut PartReader::new(&empty), empty.root().unwrap()),
        None
    );
    assert_eq!(
        read_floating(&mut PartReader::new(&empty), empty.root().unwrap()),
        None
    );
}

#[test]
fn leaves_out_a_shape_or_picture_without_a_size_with_a_warning() {
    let skipped = [("shape-skipped", 1)];
    assert_eq!(
        warning_kinds(r#"<v:rect style="position:absolute;width:10pt"/>"#),
        skipped
    );
    assert_eq!(warning_kinds(r#"<v:oval style="height:10pt"/>"#), skipped);
    assert_eq!(
        warning_kinds(r#"<v:line from="0,0" to="10pt,0"/>"#),
        skipped
    );
    assert_eq!(
        warning_kinds(
            r#"<v:shape style="position:absolute;width:auto;height:10pt"><v:imagedata r:id="a"/></v:shape>"#
        ),
        [("picture-skipped", 1)]
    );
    // A floating line takes its box from its points.
    assert_eq!(
        warning_kinds(r#"<v:line style="position:absolute" from="0,0" to="10pt,0"/>"#),
        []
    );
}

#[test]
fn reads_a_floating_picture_without_the_look_of_its_shape() {
    let doc = parse(
        r##"<v:shape type="#_x0000_t75" style="position:absolute;margin-left:378.9pt;margin-top:-10.8pt;width:95.1pt;height:32.25pt;z-index:-251659264"><v:imagedata r:id="rId1"/><w10:wrap type="square"/></v:shape>"##,
    );
    let floating = read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
    let place = (floating.h.offset, floating.v.offset);
    let size = (floating.width, floating.height);
    assert_eq!(
        place,
        (
            css::length("378.9pt").unwrap(),
            css::length("-10.8pt").unwrap()
        )
    );
    assert_eq!(size, (points(95_100), points(32_250)));
    // A square wrap keeps 9 pt at the left and the right by default.
    let wrap = Wrap::Beside {
        distances: Edges::from([points(9_000), Length::ZERO, points(9_000), Length::ZERO]),
        sides: Some(WrapSides::Both),
        polygon: None,
    };
    assert_eq!((floating.behind, floating.wrap), (true, Some(wrap)));
    assert_eq!(floating.look, None);
    let picture = floating.picture.unwrap();
    assert_eq!(picture.embed, "rId1");
    assert_eq!((picture.width, picture.height), size);
    assert!(!picture.drops);
}

#[test]
fn leaves_out_a_floating_picture_whose_colors_change() {
    // A floating picture whose colors change, such as a watermark's washout, is left out with
    // a warning.
    let washed = parse(
        r#"<v:shape style="position:absolute;width:10pt;height:10pt"><v:imagedata r:id="a" gain="19661f" blacklevel="22938f"/></v:shape>"#,
    );
    assert_eq!(
        read_floating(&mut PartReader::new(&washed), washed.root().unwrap()),
        None
    );
}

/// The kinds and counts of the warnings of reading the `w:pict` of `xml` as the run reader
/// reads it.
fn warning_kinds(xml: &str) -> Vec<(&'static str, u32)> {
    let doc = parse(xml);
    let root = doc.root().unwrap();
    let mut reader = PartReader::new(&doc);
    let _ = read(&mut reader, root);
    let mut warnings = crate::Warnings::new();
    reader.finish(&mut warnings);
    let mut kinds: Vec<_> = warnings
        .iter()
        .map(|(w, count)| (w.kind(), count))
        .collect();
    kinds.sort_unstable();
    kinds
}

#[test]
fn warns_of_what_it_leaves_out_or_draws_in_another_way() {
    let floating = "position:absolute;width:10pt;height:10pt";
    let inline = "width:10pt;height:10pt";
    let geometry = ("vml-geometry-not-supported", 1);
    let rotation = ("vml-rotation-not-supported", 1);
    let cases = [
        // A floating picture whose colors change is left out, and one in its line keeps its
        // own colors.
        (
            format!(
                r#"<v:shape style="{floating}"><v:imagedata r:id="a" gain="19661f"/></v:shape>"#
            ),
            vec![("picture-skipped", 1)],
        ),
        (
            format!(r#"<v:shape style="{inline}"><v:imagedata r:id="a" grayscale="t"/></v:shape>"#),
            vec![("vml-picture-colors-not-supported", 1)],
        ),
        // A shape of another type or with an unsupported path command warns, while a literal
        // line/curve path draws without warning.
        (
            format!(r##"<v:shape type="#_x0000_t5" style="{floating}"/>"##),
            vec![geometry],
        ),
        (
            format!(r#"<v:shape path="m0,0qb10,10e" style="{inline}"/>"#),
            vec![geometry],
        ),
        (
            format!(r#"<v:shape path="m,l10,10e" style="{inline}"/>"#),
            vec![],
        ),
        // A floating shape with arbitrary rotation draws without warning; an inline shape or
        // picture with a non-quarter rotation warns.
        (
            format!(r#"<v:rect style="{floating};rotation:45"/>"#),
            vec![],
        ),
        (
            format!(
                r#"<v:shape style="{inline};rotation:-2403486fd"><v:imagedata r:id="a"/></v:shape>"#
            ),
            vec![rotation],
        ),
        // A rotation that does not read counts as missing.
        (
            format!(r#"<v:oval style="{floating};rotation:ninety"/>"#),
            vec![("invalid-value", 1)],
        ),
        // A fill of another type than solid is drawn as a solid fill.
        (
            format!(r#"<v:rect style="{floating}"><v:fill type="gradient"/></v:rect>"#),
            vec![("value-not-supported", 1)],
        ),
        // The elements that the reader does not read.
        (
            "<v:group/><v:polyline/><v:arc/><v:curve/><v:image/>".to_owned(),
            vec![("picture-skipped", 1), ("shape-skipped", 4)],
        ),
        // A text box, a rotation of zero or of whole quarter turns, a solid fill, a fill of
        // another type that is not drawn and a picture whose colors stay give no warning.
        (
            format!(r#"<v:rect style="{floating};rotation:90"/>"#),
            vec![],
        ),
        (
            format!(
                r#"<v:shape style="{inline};rotation:-5898240fd"><v:imagedata r:id="a"/></v:shape>"#
            ),
            vec![],
        ),
        (
            format!(
                r##"<v:shape type="#_x0000_t202" style="{floating};rotation:0fd"><v:fill type="solid"/></v:shape>"##
            ),
            vec![],
        ),
        (
            r#"<v:polyline points="0,0 40pt,30pt 80pt,0" style="position:absolute;margin-left:10pt;margin-top:10pt"/>"#.to_owned(),
            vec![],
        ),
        (
            r#"<v:curve from="0,40pt" control1="20pt,0" control2="60pt,0" to="80pt,40pt" style="position:absolute;margin-left:10pt;margin-top:10pt"/>"#.to_owned(),
            vec![],
        ),
        (
            format!(r#"<v:arc startangle="0" endangle="180" style="{floating}"/>"#),
            vec![],
        ),
        (
            format!(r#"<v:rect filled="f" style="{floating}"><v:fill type="gradient"/></v:rect>"#),
            vec![],
        ),
        (
            format!(r#"<v:shape style="{inline};rotation:0"><v:imagedata r:id="a"/></v:shape>"#),
            vec![],
        ),
    ];
    for (xml, kinds) in cases {
        assert_eq!(warning_kinds(&xml), kinds, "{xml}");
    }
}

#[test]
fn warns_of_the_text_box_of_a_picture_in_its_line_and_of_a_picture_without_a_size() {
    // A shape with an image in its line is read
    // as its picture, whose text box is not read, and no other reader takes it when it has no
    // size.
    let picture = |style: &str, inside: &str| {
        format!(r#"<v:shape style="{style}"><v:imagedata r:id="a"/>{inside}</v:shape>"#)
    };
    let text =
        "<v:textbox><w:txbxContent><w:p><w:r><w:t>T</w:t></w:r></w:p></w:txbxContent></v:textbox>";
    let inline = "width:10pt;height:10pt";
    let with_text = parse(&picture(inline, text));
    assert!(matches!(
        read_inline(&mut PartReader::new(&with_text), with_text.root().unwrap()),
        Some(Content::Object {
            picture: Some(_),
            ..
        })
    ));
    let skipped = ("picture-skipped", 1);
    let cases = [
        (
            picture(inline, text),
            vec![("vml-picture-text-box-not-supported", 1)],
        ),
        // A text box without content has nothing to lay out, and a floating picture's text
        // box is read.
        (picture(inline, "<v:textbox/>"), vec![]),
        (
            picture("position:absolute;width:10pt;height:10pt", text),
            vec![],
        ),
        // Without a width or a height, or with a size below zero, the picture is left out, its
        // text box with it.
        (picture("height:10pt", ""), vec![skipped]),
        (picture("width:10pt;height:-1pt", ""), vec![skipped]),
        (picture("width:10pt", text), vec![skipped]),
    ];
    for (xml, kinds) in cases {
        assert_eq!(warning_kinds(&xml), kinds, "{xml}");
    }
}

#[test]
fn reads_the_fill_type_through_its_table() {
    assert_names(
        FILL_TYPE,
        "solid gradient gradientRadial tile pattern frame",
    );
}

#[test]
fn reads_the_anchor_lock_of_an_inline_shape() {
    let doc = parse(r#"<v:rect style="width:20pt;height:1pt"><w10:anchorlock/></v:rect>"#);
    let Some(Content::Drawing(drawing)) =
        read_inline_shape(&mut PartReader::new(&doc), doc.root().unwrap())
    else {
        panic!("no anchored drawing");
    };
    assert!(drawing.anchor_locked);
}

#[test]
fn reads_a_shape_without_a_picture_in_its_line() {
    let doc = parse(
        r#"<v:rect style="width:468pt;height:1.1pt;mso-position-vertical-relative:line" filled="f"/>"#,
    );
    let Some(Content::Drawing(drawing)) =
        read_inline_shape(&mut PartReader::new(&doc), doc.root().unwrap())
    else {
        panic!("no drawing");
    };
    assert_eq!(drawing.width, css::length("468pt").unwrap());
    assert_eq!(drawing.height, css::length("1.1pt").unwrap());
    let look = drawing.shape.look.as_ref().unwrap();
    assert_eq!(look.geometry, Geometry::Rect);
    assert!(drawing.drops);
    // A horizontal rule stands on the baseline.
    let rule = Document::parse(
        format!(
            r#"<w:pict xmlns:v="{V}" xmlns:o="{O}" xmlns:w="{W}"><v:rect style="width:10pt;height:1pt" o:hr="t"/></w:pict>"#
        )
        .as_bytes(),
        &Limits::default(),
    )
    .unwrap();
    let Some(Content::Drawing(rule)) =
        read_inline_shape(&mut PartReader::new(&rule), rule.root().unwrap())
    else {
        panic!("no rule");
    };
    assert!(!rule.drops);
    // Floating shapes and pictures are not inline shapes.
    let floating = parse(r#"<v:rect style="position:absolute;width:10pt;height:10pt"/>"#);
    assert_eq!(
        read_inline_shape(&mut PartReader::new(&floating), floating.root().unwrap()),
        None
    );
    let picture =
        parse(r#"<v:shape style="width:10pt;height:10pt"><v:imagedata r:id="a"/></v:shape>"#);
    assert_eq!(
        read_inline_shape(&mut PartReader::new(&picture), picture.root().unwrap()),
        None
    );
}

/// A shape with a fill and a text box of one paragraph, whose `v:imagedata` holds `data`, and
/// whose style holds `place` before its size.
fn shape_with_image_element(place: &str, data: &str) -> Document {
    parse(&format!(
        r##"<v:shape style="{place}width:20pt;height:10pt" fillcolor="#ff0000">{data}<v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape>"##
    ))
}

/// An image element with a title alone, which names no image, embedded or linked.
const UNTITLED: &str = r#"<v:imagedata o:title=""/>"#;

#[test]
fn reads_an_inline_shape_whose_image_element_names_no_image_as_a_shape() {
    let inline = shape_with_image_element("", UNTITLED);
    assert_eq!(
        read_inline(&mut PartReader::new(&inline), inline.root().unwrap()),
        None
    );
    let Some(Content::Drawing(drawing)) =
        read_inline_shape(&mut PartReader::new(&inline), inline.root().unwrap())
    else {
        panic!("no drawing");
    };
    assert_eq!(
        (drawing.width, drawing.height),
        (points(20_000), points(10_000))
    );
    assert!(drawing.shape.look.is_some());
    assert_eq!(drawing.shape.blocks.len(), 1);
}

#[test]
fn reads_a_floating_shape_whose_image_element_names_no_image_as_a_shape() {
    let floating = shape_with_image_element("position:absolute;", UNTITLED);
    let floating =
        read_floating(&mut PartReader::new(&floating), floating.root().unwrap()).unwrap();
    assert!(floating.picture.is_none());
    assert!(floating.look.is_some());
    assert_eq!(floating.blocks.len(), 1);
}

#[test]
fn reads_a_shape_whose_image_element_links_an_image_as_a_picture() {
    // An image element that links an image file names an image: the shape is a picture, which
    // F-Office leaves out with a warning.
    let linked = shape_with_image_element("", r#"<v:imagedata o:href="file:///a.png"/>"#);
    assert_eq!(
        read_inline_shape(&mut PartReader::new(&linked), linked.root().unwrap()),
        None
    );
    let mut reader = PartReader::new(&linked);
    assert_eq!(read_inline(&mut reader, linked.root().unwrap()), None);
    assert_eq!(
        reader.skipped_drawings(),
        [(Drawing::Picture, Reason::Unlinked, 1)]
    );
}

/// A text box behind the text, placed from the page and the paragraph, with square wrap.
fn text_box() -> Floating {
    let doc = parse(
        r##"<v:shapetype id="_x0000_t202"/><v:shape type="#_x0000_t202" filled="f" stroked="t" strokecolor="#ff0000" strokeweight="2pt" style="position:absolute;left:0;margin-left:-9.2pt;margin-top:20pt;width:100pt;height:50pt;z-index:-5;mso-position-horizontal-relative:page;mso-position-vertical-relative:text;mso-wrap-distance-left:4pt;mso-wrap-distance-right:6pt"><v:textbox inset="1pt,2pt,,4pt"><w:txbxContent><w:p><w:r><w:t>Box</w:t></w:r></w:p></w:txbxContent></v:textbox><w10:wrap type="square"/></v:shape>"##,
    );
    read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap()
}

/// An oval in the middle of the margins, 22.8 pt down the page, with top and bottom wrap.
fn oval() -> Floating {
    let doc = parse(
        r#"<v:oval style="position:absolute;margin-left:0;margin-top:22.8pt;width:37.4pt;height:30pt;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical-relative:page"><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox><w10:wrap type="topAndBottom"/></v:oval>"#,
    );
    read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap()
}

#[test]
fn places_a_text_box_from_its_style() {
    let floating = text_box();
    let place = |p: Position| (p.from, p.offset, p.align);
    assert_eq!(
        place(floating.h),
        (Relative::Area(PageArea::Page), points(-9_200), None)
    );
    assert_eq!(
        place(floating.v),
        (Relative::Paragraph, points(20_000), None)
    );
    assert_eq!(
        (floating.width, floating.height),
        (points(100_000), points(50_000))
    );
    assert!(floating.behind);
}

#[test]
fn reads_the_text_insets_and_wrap_of_a_text_box() {
    let floating = text_box();
    assert_eq!(floating.blocks.len(), 1);
    // A missing inset keeps its default of 0.1 inch at the side.
    assert_eq!(
        floating.insets,
        Edges::from([points(1_000), points(2_000), points(7_200), points(4_000)])
    );
    // A square wrap without a `side` flows the text on both sides.
    assert_eq!(
        floating.wrap,
        Some(Wrap::Beside {
            distances: Edges::from([points(4_000), Length::ZERO, points(6_000), Length::ZERO]),
            sides: Some(WrapSides::Both),
            polygon: None,
        })
    );
}

#[test]
fn reads_the_look_of_a_text_box() {
    let look = text_box().look.unwrap();
    assert_eq!(look.geometry, Geometry::Rect);
    let theme = ShapeTheme::default();
    assert_eq!(look.fill(&theme), None);
    let red = Rgb { r: 255, g: 0, b: 0 };
    assert_eq!(look.line(&theme), Some((red, Opacity::FULL, points(2_000))));
}

/// The warnings and the readings of the wrap of a shape whose `w10:wrap` has `attributes`:
/// the read invalid values, and `Some` of the sides of a wrap beside the box.
type WrapRead = (
    Option<Option<WrapSides>>,
    Vec<(String, Option<String>, ReadAs, u32)>,
);

fn read_wrap(attributes: &str) -> WrapRead {
    let doc = parse(&format!(
        r#"<v:rect style="position:absolute;width:10pt;height:10pt"><w10:wrap {attributes}/></v:rect>"#
    ));
    let mut reader = PartReader::new(&doc);
    let floating = read_floating(&mut reader, doc.root().unwrap()).unwrap();
    let sides = match floating.wrap {
        Some(Wrap::Beside { sides, .. }) => Some(sides),
        _ => None,
    };
    (sides, reader.invalid_values())
}

/// One invalid value of the attribute `name` of a `w10:wrap`, read as missing.
fn invalid_wrap(name: &str) -> Vec<(String, Option<String>, ReadAs, u32)> {
    vec![(
        "wrap".to_string(),
        Some(name.to_string()),
        ReadAs::Missing,
        1,
    )]
}

#[test]
fn reads_the_sides_of_a_square_wrap_through_their_table() {
    assert_names(WRAP_SIDE, "both left right largest");
    let (read, invalid) = (read_wrap, invalid_wrap);
    assert_eq!(
        read(r#"type="square" side="left""#),
        (Some(Some(WrapSides::Left)), vec![])
    );
    assert_eq!(
        read(r#"type="square" side="largest""#),
        (Some(Some(WrapSides::Largest)), vec![])
    );
    // Only a square wrap reads its sides.
    assert_eq!(read(r#"type="tight" side="left""#), (Some(None), vec![]));
    // Text outside the type of a side is both sides, as a missing side, with a warning.
    assert_eq!(
        read(r#"type="square" side="Left""#),
        (Some(Some(WrapSides::Both)), invalid("side"))
    );
}

#[test]
fn reads_the_type_of_a_wrap_through_its_table() {
    assert_names(WRAP_TYPE, "topAndBottom square none tight through");
    let (read, invalid) = (read_wrap, invalid_wrap);
    assert_eq!(read(r#"type="through""#), (Some(None), vec![]));
    // A wrap of none, and one whose type is text outside the type, keeps no text out.
    assert_eq!(read(r#"type="none""#), (None, vec![]));
    assert_eq!(read(r#"type="Square""#), (None, invalid("type")));
    assert_eq!(read(r#"type=" square""#), (None, invalid("type")));
}

#[test]
fn places_an_aligned_oval() {
    let floating = oval();
    let place = |p: Position| (p.from, p.align);
    assert_eq!(
        place(floating.h),
        (Relative::Area(PageArea::Margin), Some(Align::Center))
    );
    assert_eq!(place(floating.v), (Relative::Area(PageArea::Page), None));
    assert!(!floating.behind);
    assert_eq!(
        floating.insets,
        Edges::from([points(7_200), points(3_600), points(7_200), points(3_600)])
    );
    assert_eq!(
        floating.wrap,
        Some(Wrap::TopAndBottom {
            above: Length::ZERO,
            below: Length::ZERO
        })
    );
}

#[test]
fn aligns_only_with_a_value_of_the_axis_in_any_case() {
    let placed = |across: &str, down: &str| {
        let doc = parse(&format!(
            r#"<v:rect style="position:absolute;margin-left:100pt;margin-top:200pt;width:10pt;height:10pt;mso-position-horizontal:{across};mso-position-vertical:{down}"/>"#
        ));
        let floating = read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
        (floating.h.align, floating.v.align)
    };
    assert_eq!(
        placed("Right", "Bottom"),
        (Some(Align::End), Some(Align::End))
    );
    assert_eq!(
        placed("inside", "outside"),
        (Some(Align::Start), Some(Align::End))
    );
    // A value of the other axis or an unknown value leaves the offset.
    assert_eq!(placed("bottom", "right"), (None, None));
    assert_eq!(placed("top", "left"), (None, None));
    assert_eq!(placed("middle", "absolute"), (None, None));
}

#[test]
fn each_keyword_table_holds_the_keywords_of_its_property() {
    // ECMA-376 Part 4, 19.1.2.19 (`style`) and 19.1.2.22 (`v:textbox`), with the margin areas
    // that Word writes.
    assert_names(POSITION, "static absolute relative");
    assert_names(ALIGN_ACROSS, "absolute left center right inside outside");
    assert_names(ALIGN_DOWN, "absolute top center bottom inside outside");
    let areas = "inner-margin-area outer-margin-area";
    assert_names(
        RELATIVE_ACROSS,
        &format!("margin page text char left-margin-area right-margin-area {areas}"),
    );
    assert_names(
        RELATIVE_DOWN,
        &format!("margin page text line top-margin-area bottom-margin-area {areas}"),
    );
    assert_names(
        LAYOUT_FLOW,
        "horizontal vertical vertical-ideographic horizontal-ideographic",
    );
    // Part 4's four keywords, and `x y`, which Word writes and reads as both flips.
    let mut flips: Vec<_> = FLIP.names().into_iter().map(|(name, _)| name).collect();
    flips.sort_unstable();
    assert_eq!(flips, ["x", "x y", "xy", "y", "yx"]);
}

#[test]
fn mirrors_a_straight_connector_by_its_flip() {
    let connector = |declaration: &str| {
        let doc = parse(&format!(
            r##"<v:shape type="#_x0000_t32" style="position:absolute;width:10pt;height:20pt;{declaration}"/>"##
        ));
        let mut reader = PartReader::new(&doc);
        let floating = read_floating(&mut reader, doc.root().unwrap()).unwrap();
        (floating.look, reader.invalid_values().len())
    };
    let (plain, _) = connector("");
    let look = |flip| plain.clone().map(|look| look.flipped(flip));
    assert_eq!(connector("flip:X"), (look([true, false]), 0));
    assert_eq!(connector("flip:yx"), (look([true, true]), 0));
    assert_eq!(connector("flip:x y"), (look([true, true]), 0));
    assert_ne!(look([true, true]), plain);
    // Other text counts as missing, no flip, with a warning.
    assert_eq!(connector("flip:x,y"), (plain, 1));
}

#[test]
fn turns_a_shape_and_a_picture_by_whole_quarter_turns_and_arbitrary_floating_angles() {
    let floating = |kind: &str, declaration: &str, inside: &str| {
        let doc = parse(&format!(
            r#"<v:shape {kind} style="position:absolute;width:25pt;height:10pt;{declaration}">{inside}</v:shape>"#
        ));
        let mut reader = PartReader::new(&doc);
        read_floating(&mut reader, doc.root().unwrap()).unwrap()
    };
    let connector = |declaration: &str| floating(r##"type="#_x0000_t32""##, declaration, "").look;
    let plain = connector("");
    let turned = |rotation: i64| plain.clone().map(|look| look.turned(rotation));
    for (declaration, angle) in [
        ("rotation:90", QUARTER_TURN),
        ("rotation:-90", 3 * QUARTER_TURN),
        ("rotation:180.0", 2 * QUARTER_TURN),
        ("rotation:450", QUARTER_TURN),
        ("rotation:5898240fd", QUARTER_TURN),
        ("rotation:0", 0),
        ("rotation:45", QUARTER_TURN / 2),
        ("rotation:x", 0),
    ] {
        assert_eq!(connector(declaration), turned(angle), "{declaration}");
    }
    // VML rotates first and flips second, so flip:x negates the DrawingML rotation.
    assert_eq!(
        connector("flip:x;rotation:2949120fd"),
        plain
            .clone()
            .map(|look| look.flipped([true, false]).turned(7 * (QUARTER_TURN / 2)))
    );
    // An uncropped floating picture turns by any angle about its box center.
    let image = r#"<v:imagedata r:id="a"/>"#;
    let picture = |declaration: &str| floating("", declaration, image).picture.unwrap();
    assert_eq!(picture("").turn, None);
    assert_eq!(picture("rotation:90").turn, turn(1, [false; 2]));
    assert!(picture("rotation:35").turn.is_some());
}

#[test]
fn rotates_floating_vml_group_children_about_group_center() {
    let doc = parse(
        r#"<v:group coordorigin="0,0" coordsize="1000,1000" style="position:absolute;margin-left:220pt;margin-top:200pt;width:120pt;height:80pt;rotation:90">
            <v:rect style="position:absolute;left:0;top:0;width:500;height:300"/>
        </v:group>"#,
    );
    let mut reader = PartReader::new(&doc);
    let group = read_floating(&mut reader, doc.root().unwrap()).unwrap();
    assert_eq!(group.parts.len(), 1);
    let (left, top, child) = &group.parts[0];
    // Original child (0, 0, 60pt, 24pt) has center (30pt, 12pt); rotating 90 deg CW about
    // group center (60pt, 40pt) places its center at (88pt, 10pt) => origin (58pt, -2pt).
    assert_eq!((*left, *top), (points(58_000), points(-2_000)));
    assert_eq!(child.look.as_ref().unwrap().quarter_turns(), Some(1));
}

#[test]
fn turns_a_picture_and_a_shape_in_their_line_by_whole_quarter_turns() {
    let image = r#"<v:imagedata r:id="a"/>"#;
    let inline = |declaration: &str, inside: &str| {
        let doc = parse(&format!(
            r#"<v:shape style="width:25pt;height:10pt;{declaration}">{inside}</v:shape>"#
        ));
        read(&mut PartReader::new(&doc), doc.root().unwrap())
    };
    let Some(Content::Object {
        picture: Some(picture),
        ..
    }) = inline("rotation:90", image)
    else {
        panic!("no picture in its line");
    };
    assert_eq!(picture.turn, turn(1, [false; 2]));
    let inline_look = |declaration: &str| match inline(declaration, "") {
        Some(Content::Drawing(drawing)) => drawing.shape.look.clone(),
        _ => panic!("no shape in its line"),
    };
    let upright = inline_look("");
    assert_eq!(
        inline_look("rotation:90"),
        upright.clone().map(|look| look.turned(QUARTER_TURN))
    );
    assert_ne!(inline_look("rotation:90"), upright);
}

#[test]
fn warns_of_the_text_of_a_turned_shape_once() {
    // A turned shape's text is laid out upright, with the warning of a turned text box, once
    // also when its text runs down the box.
    let text = "<w:txbxContent><w:p/></w:txbxContent>";
    let turned = |declaration: &str, flow: &str| {
        warning_kinds(&format!(
            r#"<v:rect style="position:absolute;width:10pt;height:10pt;{declaration}"><v:textbox style="{flow}">{text}</v:textbox></v:rect>"#
        ))
    };
    let warned = vec![("turned-text-box-not-supported", 1)];
    assert_eq!(turned("rotation:90", ""), warned);
    assert_eq!(turned("rotation:90", "layout-flow:vertical"), warned);
    assert_eq!(turned("rotation:180", ""), warned);
    assert_eq!(turned("rotation:360", ""), vec![]);
}

/// The place across and down of a floating `v:rect` with the CSS declarations `declarations`,
/// with the warnings of the values that do not read and of those drawn as another value.
type Placed = (
    (Relative, Relative),
    Vec<(String, Option<String>, ReadAs, u32)>,
    Vec<(String, Option<String>, &'static str, u32)>,
);

fn placed(declarations: &str) -> Placed {
    let doc = parse(&format!(
        r#"<v:rect style="position:absolute;width:10pt;height:10pt;{declarations}"/>"#
    ));
    let mut reader = PartReader::new(&doc);
    let floating = read_floating(&mut reader, doc.root().unwrap()).unwrap();
    (
        (floating.h.from, floating.v.from),
        reader.invalid_values(),
        reader.unsupported_values(),
    )
}

#[test]
fn reads_the_relative_keywords_in_any_case_and_warns_with_the_property() {
    let property = |name: &str| Some(format!("style mso-position-{name}-relative"));
    // A keyword reads in any case, and a missing keyword means `text`: across, the text column,
    // which F-Office draws as the margins (`across`), and down, the paragraph.
    assert_eq!(
        placed("mso-position-horizontal-relative:PAGE;mso-position-vertical-relative:Margin"),
        (
            (
                Relative::Area(PageArea::Page),
                Relative::Area(PageArea::Margin)
            ),
            vec![],
            vec![]
        )
    );
    assert_eq!(
        placed(""),
        (
            (Relative::Area(PageArea::Margin), Relative::Paragraph),
            vec![],
            vec![]
        )
    );
    // `text` across is drawn as the margins with no warning here: the body's reader warns where
    // the text column can lie apart from them (`warn_text_column`). `char` and `line` are
    // drawn as another place, with a warning.
    let (from, invalid, unsupported) =
        placed("mso-position-horizontal-relative:text;mso-position-vertical-relative:line");
    assert_eq!(
        (from, invalid),
        (
            (Relative::Area(PageArea::Margin), Relative::Paragraph),
            vec![]
        )
    );
    assert_eq!(
        unsupported,
        [("rect".into(), property("vertical"), "line", 1)]
    );
    assert_eq!(
        placed("mso-position-horizontal-relative:char").2,
        [("rect".into(), property("horizontal"), "char", 1)]
    );
    // Text outside the keywords, such as `paragraph` down, counts as missing, with a warning.
    let (from, invalid, unsupported) =
        placed("mso-position-horizontal-relative:line;mso-position-vertical-relative:paragraph");
    assert_eq!(
        (from, unsupported),
        (
            (Relative::Area(PageArea::Margin), Relative::Paragraph),
            vec![]
        )
    );
    assert_eq!(
        invalid,
        [
            ("rect".into(), property("horizontal"), ReadAs::Missing, 1),
            ("rect".into(), property("vertical"), ReadAs::Missing, 1),
        ]
    );
}

#[test]
fn a_keyword_of_the_other_axis_down_the_page_counts_as_missing() {
    let property = |name: &str| Some(format!("style mso-position-{name}-relative"));
    // A keyword of the other axis down, such as `char` or `left-margin-area`, counts as missing:
    // the paragraph, not the margin or a margin area.
    for keyword in ["char", "left-margin-area"] {
        assert_eq!(
            placed(&format!("mso-position-vertical-relative:{keyword}")),
            (
                (Relative::Area(PageArea::Margin), Relative::Paragraph),
                vec![("rect".into(), property("vertical"), ReadAs::Missing, 1)],
                vec![]
            ),
            "{keyword}"
        );
    }
}

#[test]
fn draws_the_text_column_across_as_the_margins_and_notes_the_shape() {
    let noted = |declarations: &str| {
        let doc = parse(&format!(
            r#"<v:rect style="position:absolute;width:10pt;height:10pt;{declarations}"/>"#
        ));
        let mut reader = PartReader::new(&doc);
        let floating = read_floating(&mut reader, doc.root().unwrap()).unwrap();
        (floating.h.from, reader.take_text_columns().len())
    };
    // The keyword `text` in any case, no keyword, and an unknown keyword, which counts as
    // missing, are the text column.
    for declarations in [
        "",
        "mso-position-horizontal-relative:Text",
        "mso-position-horizontal-relative:line",
    ] {
        assert_eq!(
            noted(declarations),
            (Relative::Area(PageArea::Margin), 1),
            "{declarations}"
        );
    }
    for keyword in ["margin", "char"] {
        let declarations = format!("mso-position-horizontal-relative:{keyword}");
        assert_eq!(
            noted(&declarations),
            (Relative::Area(PageArea::Margin), 0),
            "{keyword}"
        );
    }
}

#[test]
fn a_missing_relative_keyword_means_the_tables_text() {
    // ECMA-376 Part 4, 19.1.2.19: `text` is the default of both axes.
    for axis in [ACROSS, DOWN] {
        let (_, table) = axis.relative;
        assert_eq!(
            table.find("text").map(|(case, _, _)| *case),
            Some(axis.text)
        );
    }
}

#[test]
fn leaves_out_a_later_shape_and_a_picture_in_its_line_outside_v_shape_with_a_warning() {
    let picture = |element: &str, style: &str| {
        format!(
            r#"<v:{element} style="{style}width:10pt;height:10pt"><v:imagedata r:id="a"/></v:{element}>"#
        )
    };
    assert_eq!(
        warning_kinds(&picture("rect", "")),
        [("picture-skipped", 1)]
    );
    // A floating picture reads from any shape element.
    assert_eq!(warning_kinds(&picture("rect", "position:absolute;")), []);
    // Only the first shape of a `w:pict` is read.
    assert_eq!(
        warning_kinds(&format!(
            r#"<v:rect style="width:10pt;height:10pt"/>{}<v:oval/>"#,
            picture("shape", "")
        )),
        [("picture-skipped", 1), ("shape-skipped", 1)]
    );
}

#[test]
fn reads_the_position_of_a_shape_once() {
    let position = Some("style position".to_string());
    // A floating keyword in another case floats.
    let upper = parse(r#"<v:rect style="position:ABSOLUTE;width:10pt;height:10pt"/>"#);
    assert!(read_floating(&mut PartReader::new(&upper), upper.root().unwrap()).is_some());
    // Text outside the keywords stands in the line, with one warning.
    let other = parse(r#"<v:rect style="position:fixed;width:10pt;height:10pt"/>"#);
    let mut reader = PartReader::new(&other);
    assert!(matches!(
        read(&mut reader, other.root().unwrap()),
        Some(Content::Drawing(_))
    ));
    assert_eq!(
        reader.invalid_values(),
        [("rect".into(), position.clone(), ReadAs::Missing, 1)]
    );
    // `relative` stands in the line, drawn as `static`, with one warning.
    let relative = parse(r#"<v:rect style="position:relative;width:10pt;height:10pt"/>"#);
    let mut reader = PartReader::new(&relative);
    assert!(read(&mut reader, relative.root().unwrap()).is_some());
    assert_eq!(
        reader.unsupported_values(),
        [("rect".into(), position, "relative", 1)]
    );
}

#[test]
fn turns_a_text_box_by_its_layout_flow_in_any_case() {
    let kinds = |flow: &str| {
        warning_kinds(&format!(
            r#"<v:rect style="position:absolute;width:10pt;height:10pt"><v:textbox style="layout-flow:{flow}"><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:rect>"#
        ))
    };
    let turned = [("turned-text-box-not-supported", 1)];
    assert_eq!(kinds("Vertical"), turned);
    assert_eq!(kinds("vertical-ideographic"), turned);
    assert_eq!(kinds("horizontal-ideographic"), []);
    assert_eq!(kinds("upright"), [("invalid-value", 1)]);
}

#[test]
fn gives_an_oval_the_default_look() {
    let look = oval().look.unwrap();
    assert_eq!(look.geometry, Geometry::Ellipse);
    let theme = ShapeTheme::default();
    let white = Rgb {
        r: 255,
        g: 255,
        b: 255,
    };
    assert_eq!(look.fill(&theme), Some((white, Opacity::FULL)));
    assert_eq!(
        look.line(&theme),
        Some((Rgb::BLACK, Opacity::FULL, points(750)))
    );
}

#[test]
fn counts_a_color_that_does_not_read_as_missing() {
    let doc = parse(
        r#"<v:rect style="position:absolute;width:10pt;height:10pt" fillcolor="sea" strokecolor="red"><v:stroke color="sky"/></v:rect>"#,
    );
    let mut reader = PartReader::new(&doc);
    let look = read_floating(&mut reader, doc.root().unwrap())
        .unwrap()
        .look
        .unwrap();
    let theme = ShapeTheme::default();
    let red = Rgb { r: 255, g: 0, b: 0 };
    // The fill takes the default, white, and the stroke's color counts as missing, so the
    // shape's `strokecolor` gives the line's.
    assert_eq!(
        (look.fill(&theme), look.line(&theme)),
        (
            Some((Rgb::WHITE, Opacity::FULL)),
            Some((red, Opacity::FULL, points(750)))
        )
    );
    assert_eq!(
        reader.invalid_values(),
        [
            ("rect".into(), Some("fillcolor".into()), ReadAs::Missing, 1),
            ("stroke".into(), Some("color".into()), ReadAs::Missing, 1),
        ]
    );
}

#[test]
fn reads_a_line_between_its_points() {
    let doc = parse(
        r#"<v:line from="51.65pt,13.1pt" to="401.8pt,12.85pt" strokeweight=".5pt" style="position:absolute;mso-position-horizontal-relative:text;mso-position-vertical-relative:text"/>"#,
    );
    let line = read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
    // The box runs from the left and upper point, and the line up to the right.
    assert_eq!(line.h.offset, css::length("51.65pt").unwrap());
    assert_eq!(line.v.offset, css::length("12.85pt").unwrap());
    assert_eq!(line.width, css::length("350.15pt").unwrap());
    assert_eq!(line.height, css::length("0.25pt").unwrap());
    let look = line.look.unwrap();
    assert_eq!(look.geometry, Geometry::Line);
    assert_eq!(
        look.line(&ShapeTheme::default()),
        Some((Rgb::BLACK, Opacity::FULL, points(500)))
    );
}

#[test]
fn reads_a_straight_connector_with_the_weight_of_its_stroke() {
    let doc = parse(
        r##"<v:shape type="#_x0000_t32" style="position:absolute;margin-left:-5.2pt;margin-top:24.95pt;width:464.6pt;height:0;flip:y"><v:stroke weight="0.1pt"/></v:shape>"##,
    );
    let line = read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
    assert_eq!(line.width, css::length("464.6pt").unwrap());
    let look = line.look.unwrap();
    assert_eq!(look.geometry, Geometry::Line);
    assert_eq!(
        look.line(&ShapeTheme::default()),
        Some((Rgb::BLACK, Opacity::FULL, points(100)))
    );
    // A stroke that is off draws no line.
    let off = parse(
        r##"<v:shape type="#_x0000_t32" style="position:absolute;width:10pt;height:0"><v:stroke on="f"/></v:shape>"##,
    );
    let look = read_floating(&mut PartReader::new(&off), off.root().unwrap())
        .unwrap()
        .look
        .unwrap();
    assert_eq!(look.line(&ShapeTheme::default()), None);
}

#[test]
fn reads_the_corners_of_a_rounded_rectangle() {
    let doc = parse(
        r#"<v:roundrect arcsize="10923f" style="position:absolute;width:10pt;height:10pt"/>"#,
    );
    let floating = read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
    assert_eq!(floating.look.unwrap().geometry, Geometry::RoundRect(8_333));
    // Without a wrap, the shape does not move the text.
    assert_eq!(floating.wrap, None);
    let doc =
        parse(r##"<v:shape type="#_x0000_t5" style="position:absolute;width:10pt;height:10pt"/>"##);
    let floating = read_floating(&mut PartReader::new(&doc), doc.root().unwrap()).unwrap();
    assert_eq!(floating.look.unwrap().geometry, Geometry::Other);
}

#[test]
fn reads_a_value_that_does_not_read_as_missing_with_a_warning() {
    // A corner size, a CSS offset, z-index or wrap distance, and an inset of a text box that
    // do not read count as missing: each takes its default, with a warning.
    let doc = parse(
        r#"<v:roundrect arcsize="x" style="position:absolute;margin-left:x;width:10pt;height:10pt;z-index:x;mso-wrap-distance-left:x"><v:textbox inset="x,2pt"><w:txbxContent><w:p/></w:txbxContent></v:textbox><w10:wrap type="square"/></v:roundrect>"#,
    );
    let mut reader = PartReader::new(&doc);
    let floating = read_floating(&mut reader, doc.root().unwrap()).unwrap();
    let plain = parse(
        r#"<v:roundrect style="position:absolute;width:10pt;height:10pt"><v:textbox inset=",2pt"><w:txbxContent><w:p/></w:txbxContent></v:textbox><w10:wrap type="square"/></v:roundrect>"#,
    );
    let mut plain_reader = PartReader::new(&plain);
    let defaults = read_floating(&mut plain_reader, plain.root().unwrap()).unwrap();
    assert_eq!(plain_reader.invalid_values(), []);
    assert_eq!(
        (
            floating.look.map(|look| look.geometry),
            floating.h,
            floating.behind
        ),
        (
            defaults.look.map(|look| look.geometry),
            defaults.h,
            defaults.behind
        )
    );
    assert_eq!(
        (floating.wrap, floating.insets),
        (defaults.wrap, defaults.insets)
    );
    let mut invalid = reader.invalid_values();
    invalid.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
    let missing = |element: &str, place: &str| {
        (
            element.to_string(),
            Some(place.to_string()),
            ReadAs::Missing,
            1,
        )
    };
    assert_eq!(
        invalid,
        [
            missing("roundrect", "arcsize"),
            missing("roundrect", "style margin-left"),
            missing("roundrect", "style mso-wrap-distance-left"),
            missing("roundrect", "style z-index"),
            missing("textbox", "inset"),
        ]
    );
}

#[test]
fn crops_nothing_on_a_side_whose_crop_does_not_read() {
    let crop = |value: &str| {
        let doc = parse(&format!(
            r#"<v:shape style="width:10pt;height:10pt"><v:imagedata r:id="a" cropleft="{value}" croptop="5000f"/></v:shape>"#
        ));
        let mut reader = PartReader::new(&doc);
        let Some(Content::Object { picture, .. }) = read_inline(&mut reader, doc.root().unwrap())
        else {
            panic!("no picture");
        };
        let crop = picture.unwrap().crop;
        (crop.left, crop.top, reader.invalid_values().len())
    };
    assert_eq!(crop("0"), (0, 7_629, 0));
    assert_eq!(crop("x"), (0, 7_629, 1));
}

#[test]
fn reads_the_line_of_text_of_a_watermark_with_its_fill_and_rotation() {
    let doc = parse(
        r##"<v:shape id="w" o:spid="_x0000_s1" type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:412.4pt;height:137.45pt;rotation:315;z-index:-251657216;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" fillcolor="silver" stroked="f"><v:fill opacity=".5"/><v:textpath style="font-family:&quot;Calibri&quot;;font-size:1pt" string="DRAFT"/></v:shape>"##,
    );
    let with = |text_path| {
        let mut reader = PartReader::new(&doc).with_vml_sizes(VmlSizes::with_text_path(text_path));
        read_floating(&mut reader, doc.root().unwrap()).unwrap()
    };
    // A target that reads no text path draws the shape's own look.
    let shape = with(VmlTextPath::ShapeLook);
    assert!(shape.text_path.is_none() && shape.look.is_some());
    let floating = with(VmlTextPath::InkAligned);
    let path = floating.text_path.unwrap();
    // Silver at half its opacity on white.
    let gray = Rgb {
        r: 224,
        g: 224,
        b: 224,
    };
    assert_eq!(
        (
            path.string.as_str(),
            path.face.as_str(),
            path.color,
            path.rotation
        ),
        ("DRAFT", "Calibri", gray, 315 * QUARTER_TURN / 90)
    );
    // The line takes the place of the shape, and its box keeps its size, unturned.
    assert_eq!(
        (
            floating.look,
            floating.width,
            floating.height,
            floating.behind
        ),
        (
            None,
            css::length("412.4pt").unwrap(),
            css::length("137.45pt").unwrap(),
            true
        )
    );
}

#[test]
fn reads_no_line_of_text_from_a_shape_of_another_type() {
    let doc = parse(
        r##"<v:shape type="#_x0000_t202" style="position:absolute;width:10pt;height:10pt"><v:textpath style="font-family:Calibri" string="A"/></v:shape>"##,
    );
    let mut reader =
        PartReader::new(&doc).with_vml_sizes(VmlSizes::with_text_path(VmlTextPath::InkAligned));
    let floating = read_floating(&mut reader, doc.root().unwrap()).unwrap();
    assert_eq!(floating.text_path, None);
}

#[test]
fn reads_floating_nested_flipped_and_inline_vml_groups() {
    let pt = |n: i64| Length::from_points(n).unwrap();
    let xml = concat!(
        r#"<v:group style="position:absolute;margin-left:10pt;margin-top:20pt;width:120pt;height:60pt;flip:x" coordorigin="100,200" coordsize="240,120">"#,
        r#"<v:rect style="position:absolute;left:100;top:200;width:80;height:60"/>"#,
        r#"<v:line from="120,220" to="300,280"/>"#,
        r#"<v:group style="position:absolute;left:140;top:200;width:100;height:120" coordorigin="0,0" coordsize="100,100">"#,
        r#"<v:oval style="position:absolute;left:0pt;top:50pt;width:50pt;height:50pt"/>"#,
        r#"</v:group>"#,
        r#"</v:group>"#,
    );
    let doc = parse(xml);
    let mut reader = PartReader::new(&doc);
    let Some(Content::Floating(group)) = super::read(&mut reader, doc.root().unwrap()) else {
        panic!("expected floating v:group");
    };
    assert_eq!(group.parts.len(), 3);
    // Rect (100..180 -> local 0..80, flipped -> 160..240 -> 80..120 pt, w=40pt, h=30pt).
    assert_eq!(
        (
            group.parts[0].0,
            group.parts[0].1,
            group.parts[0].2.width,
            group.parts[0].2.height
        ),
        (pt(80), pt(0), pt(40), pt(30))
    );
    // Line (120..300 -> local 20..200, flipped -> 220..40 -> 110..20 pt, w=90pt, h=30pt).
    assert_eq!(
        (
            group.parts[1].0,
            group.parts[1].1,
            group.parts[1].2.width,
            group.parts[1].2.height
        ),
        (pt(20), pt(10), pt(90), pt(30))
    );
    // Nested group (140..240 -> flipped 100..200 -> 50..100 pt) with oval (0..50 flipped -> 25..50 pt).
    assert_eq!(
        (
            group.parts[2].0,
            group.parts[2].1,
            group.parts[2].2.width,
            group.parts[2].2.height
        ),
        (pt(75), pt(30), pt(25), pt(30))
    );

    // Inline v:group with omitted coordsize uses default 1000x1000.
    let inline_xml = concat!(
        r#"<v:group style="width:100pt;height:50pt">"#,
        r#"<v:rect style="position:absolute;left:100;top:200;width:400;height:500"/>"#,
        r#"</v:group>"#,
    );
    let doc = parse(inline_xml);
    let mut reader = PartReader::new(&doc);
    let Some(Content::Drawing(inline)) = super::read(&mut reader, doc.root().unwrap()) else {
        panic!("expected inline v:group");
    };
    assert_eq!(inline.shape.parts.len(), 1);
    assert_eq!(
        (
            inline.shape.parts[0].0,
            inline.shape.parts[0].1,
            inline.shape.parts[0].2.width,
            inline.shape.parts[0].2.height
        ),
        (pt(10), pt(10), pt(40), pt(25))
    );
}

#[test]
fn reads_shapetype_formula_paths_limo_and_implicit_presets() {
    let xml = concat!(
        r#"<v:shapetype id="_x0000_t13" coordsize="21600,21600" adj="16200,5400" path="m@0,l@0@1,0@1,0@2@0@2@0,21600,21600,10800xe">"#,
        r#"<v:formulas><v:f eqn="val #0"/><v:f eqn="val #1"/><v:f eqn="sum height 0 #1"/></v:formulas>"#,
        r#"</v:shapetype>"#,
        r##"<v:shape type="#_x0000_t13" style="position:absolute;width:120pt;height:60pt"/>"##,
    );
    let doc = parse(xml);
    let mut reader = PartReader::new(&doc);
    let Some(Content::Floating(arrow)) = super::read(&mut reader, doc.root().unwrap()) else {
        panic!("expected floating arrow");
    };
    assert!(matches!(
        arrow.look.as_ref().map(|l| &l.geometry),
        Some(Geometry::Custom(_))
    ));
    assert_eq!(warning_kinds(xml), vec![]);

    // Implicit #_x0000_t3 without a v:shapetype reads as an ellipse with no warning.
    let oval_xml =
        r##"<v:shape type="#_x0000_t3" style="position:absolute;width:60pt;height:40pt"/>"##;
    let doc = parse(oval_xml);
    let mut reader = PartReader::new(&doc);
    let Some(Content::Floating(oval)) = super::read(&mut reader, doc.root().unwrap()) else {
        panic!("expected floating oval");
    };
    assert_eq!(
        oval.look.as_ref().map(|l| &l.geometry),
        Some(&Geometry::Ellipse)
    );
    assert_eq!(warning_kinds(oval_xml), vec![]);
}