f-office-docx 0.2.4

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
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
//! VML (`w:pict` and `w:object`), the older drawing markup of ECMA-376 Part 4: pictures in
//! their text line, and floating shapes, groups, and text boxes.

mod group;

use std::rc::Rc;

use f_office_drawingml::color::on_white;
use f_office_drawingml::custom::{CustomGeometry, LiteralPath, LiteralStep};
use f_office_drawingml::effect::{ShadowColor, ShadowOffset};
use f_office_drawingml::shape::{Geometry, ShapeLook, quarter_turns};
use f_office_drawingml::theme::ShapeTheme;
use f_office_fonts::FamilyName;
use f_office_paint::{Opacity, Rgb};
use f_office_units::scale::{FULL_TURN, QUARTER_TURN};
use f_office_units::{Edges, Length, div_round_i128};
use f_office_vml::css::{self, Style};
use f_office_vml::path as vml_path;
use f_office_vml::shape_type::{self, COORDINATES, TextRect};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::body::{Content, InlineDrawing, read_story};
use crate::enumerations::style_place;
use crate::floating::{
    Floating, InsetEdge, PageArea, Position, Relative, TextFlow, TextPath, VmlShadow, Wrap,
    WrapSides,
};
use crate::ns::{self, O, R, V, W, W10};
use crate::params::{
    VML_ARC_SIZE, VML_SHADOW_COLOR, VML_SHADOW_OFFSET, VML_STROKE_WEIGHT, VML_TEXT_BOX_INSETS,
    VML_WRAP_DISTANCE,
};
use crate::picture::{Picture, VML_IMAGE, any_turn, embedded_image, scale_to_original, turn};
use crate::props::Align;
use crate::reader::settings::{InlineVml, InlineVmlKind, VmlHolder};
use crate::reader::{PartReader, attribute};
use crate::warnings::{Drawing, Feature, ReadAs, Reason};

/// Reads a `w:pict` or `w:object` `node`: its first shape (one of [`SHAPES`]), as a floating
/// drawing when the CSS `position` of its style is `absolute` ([`read_floating`]), and else in
/// its text line, as a picture ([`read_inline`]) or as a shape without one
/// ([`read_inline_shape`]). The reader reads `position` once, through its table, so that a
/// keyword that does not read warns once. An image element (`v:image`) is left out with a warning
/// ([`UNREAD`]). A shape after the first is left out with a warning too. A `w:object` with an
/// `o:OLEObject` holds the preview of an embedded object ([`VmlHolder::EmbeddedObject`]), with
/// the object's original size ([`original_size`]).
pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Option<Content> {
    let doc = reader.doc;
    skip_unread(reader, node);
    let mut shapes = doc.child_elements(node).filter(|child| {
        doc.is(*child, V, "group") || SHAPES.iter().any(|name| doc.is(*child, V, name))
    });
    let shape = shapes.next()?;
    for later in shapes {
        let drawing = if image_data(doc, later).is_some() {
            Drawing::Picture
        } else {
            Drawing::Shape
        };
        reader.drawing_skipped(drawing, Reason::Unsupported);
    }
    let style = Style::new(doc.attribute(shape, None, "style").unwrap_or(""));
    let holder = if doc.is(node, W, "object") && doc.child(node, O, "OLEObject").is_some() {
        VmlHolder::EmbeddedObject {
            original: original_size(reader, node),
        }
    } else {
        VmlHolder::Picture
    };
    if doc.is(shape, V, "group") {
        return match reader.style_keyword(shape, &style, "position", POSITION) {
            Some(CssPosition::Floating) => group::read_floating(reader, shape, &style)
                .map(|floating| Content::Floating(Box::new(floating))),
            Some(CssPosition::InLine) | None => group::read_inline(reader, shape, &style),
        };
    }
    match reader.style_keyword(shape, &style, "position", POSITION) {
        Some(CssPosition::Floating) => read_floating(reader, shape, &style)
            .map(|floating| Content::Floating(Box::new(floating))),
        Some(CssPosition::InLine) | None => read_inline(reader, shape, &style, holder)
            .or_else(|| read_inline_shape(reader, shape, &style)),
    }
}

/// How a VML shape stands, as the CSS `position` of its style says.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CssPosition {
    /// In its text line.
    InLine,
    /// Out of its text line, at its place on the page: a floating drawing.
    Floating,
}

/// The values of `position` in a VML shape's style (ECMA-376 Part 4, 19.1.2.19): `static` stands
/// in the text line, and `absolute` floats; `relative`, in the line and moved by its offsets, is
/// drawn in the line without them. A missing value is `static`.
const POSITION: &Values<CssPosition> = &Values::new(&[
    own("static", CssPosition::InLine),
    own("absolute", CssPosition::Floating),
    another("relative", CssPosition::InLine),
]);

/// Reads a picture in its text line: a `v:shape` `shape` with a `v:imagedata` that names an
/// image ([`image_data`]), whose CSS `style` gives its size. Anything else gives `None`, a
/// linked image with a warning ([`embedded_image`]), and such a picture without a CSS width or
/// height, or in another element than `v:shape`, with a warning too, since no other reader takes
/// a shape with an image in its line. The shape's text box is not read, with a warning
/// ([`Feature::VmlPictureTextBox`]). The picture takes its CSS size; the target's quirk
/// `VmlPictureRoom` says, through the reader's VML sizes, whether a picture that `holder` holds
/// takes its size and its room from its image once the reader attaches the image.
fn read_inline(
    reader: &mut PartReader,
    shape: NodeId,
    style: &Style,
    holder: VmlHolder,
) -> Option<Content> {
    let doc = reader.doc;
    let data = image_data(doc, shape)?;
    if !doc.is(shape, V, "shape") {
        reader.drawing_skipped(Drawing::Picture, Reason::Unsupported);
        return None;
    }
    let embed = embedded_image(reader, data, VML_IMAGE)?;
    // quirk: VmlObjectSize::TakesStyleSize (src/quirks.rs)
    let (Some(width), Some(height)) = (size(style, "width"), size(style, "height")) else {
        reader.drawing_skipped(Drawing::Picture, Reason::Unsupported);
        return None;
    };
    if changes_colors(doc, data) {
        reader.feature_not_supported(Feature::VmlPictureColors);
    }
    let text_box = doc.child(shape, V, "textbox");
    if text_box.is_some_and(|text_box| ns::text_box_content(doc, text_box).is_some()) {
        reader.feature_not_supported(Feature::VmlPictureTextBox);
    }
    let quarters = quarter_turns_of(reader, shape, style);
    let mut picture = Picture {
        drops: true,
        turn: turn(quarters, [false; 2]),
        // quirk: VmlPictureRoom::NaturalScale (src/quirks.rs)
        scale_steps: reader.vml_sizes().picture_scale(holder),
        ..picture(reader, embed, data, width, height)
    };
    let (mut width, mut height) = (width, height);
    // quirk: VmlPreviewRoom::OriginalScale (src/quirks.rs)
    if let (
        VmlHolder::EmbeddedObject {
            original: Some(original),
        },
        Some(steps),
    ) = (holder, reader.vml_sizes().preview_scale())
    {
        scale_to_original(&mut picture, (&mut width, &mut height), original, steps);
    }
    Some(Content::Object {
        width,
        height,
        picture: Some(Box::new(picture)),
        extent: None,
    })
}

/// The original size of the embedded object of a `w:object` `node` (`w:dxaOrig`, `w:dyaOrig`),
/// across and down in twips, when it gives both.
fn original_size(reader: &mut PartReader, node: NodeId) -> Option<(Length, Length)> {
    Some((
        reader.twips(node, "dxaOrig")?,
        reader.twips(node, "dyaOrig")?,
    ))
}

/// The image element (`v:imagedata`) of a shape when it names an image, embedded (`r:id`) or
/// linked (`o:href`). One that names no image has nothing to draw, so the shape reads as a
/// shape without one, with its fill, its line and its text box.
fn image_data(doc: &Document, shape: NodeId) -> Option<NodeId> {
    let (embed, (link_namespace, link)) = VML_IMAGE;
    doc.child(shape, V, "imagedata").filter(|&data| {
        doc.attribute(data, Some(R), embed).is_some()
            || doc.attribute(data, Some(link_namespace), link).is_some()
    })
}

/// The picture of a `v:imagedata` of the image part `embed`, which fills the box of its shape,
/// `width` by `height`, with its crop.
fn picture(
    reader: &mut PartReader,
    embed: &str,
    data: NodeId,
    width: Length,
    height: Length,
) -> Picture {
    Picture::new(embed, Edges::sized(width, height), crop(reader, data))
}

/// The parts of a picture that its `v:imagedata` cuts off at the left, top, right and bottom
/// (`cropleft`, `croptop`, `cropright`, `cropbottom`), as fractions of the image in
/// 100,000ths, the unit of DrawingML's `a:srcRect`. The rest of the image fills the box. A
/// crop that does not read cuts nothing, with a warning.
fn crop(reader: &mut PartReader, data: NodeId) -> Edges<i64> {
    Edges::from(
        ["cropleft", "croptop", "cropright", "cropbottom"].map(|name| {
            reader
                .or_missing_in(data, (None, name), css::fraction)
                .unwrap_or(0)
        }),
    )
}

/// The length of the CSS property `name` of a shape's `style`, such as its `width`: a size
/// below zero counts as missing. A shape or a picture without a size is left out with its own
/// warning, so a size that does not read gives no other.
fn size(style: &Style, name: &str) -> Option<Length> {
    style
        .get(name)
        .and_then(css::length)
        .filter(|length| length.units() >= 0)
}

/// The VML shapes that F-Office reads as floating drawings.
const SHAPES: [&str; 8] = [
    "shape",
    "rect",
    "roundrect",
    "oval",
    "line",
    "polyline",
    "arc",
    "curve",
];

/// The shape type of a straight connector (`o:spt="32"`), which draws a line across its box.
const STRAIGHT_CONNECTOR: &str = "_x0000_t32";

/// Whether a shape is a line: a `v:line`, or a `v:shape` of the straight connector type.
fn is_line(doc: &Document, shape: NodeId) -> bool {
    doc.is(shape, V, "line")
        || doc
            .attribute(shape, None, "type")
            .map(|t| t.trim_start_matches('#'))
            == Some(STRAIGHT_CONNECTOR)
}

/// Reads a shape `shape` without a picture in its text line, whose CSS `style` gives its size.
/// A shape whose `v:imagedata` names no image is one without a picture ([`image_data`]). It
/// takes room on the line as an inline picture does, and Word draws it there with its fill,
/// its line and its text box. A shape without a CSS width or height is left out with a
/// warning, and anything else gives `None`.
fn read_inline_shape(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<Content> {
    let doc = reader.doc;
    if image_data(doc, shape).is_some() {
        return None;
    }
    let (Some(width), Some(height)) = (size(style, "width"), size(style, "height")) else {
        reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
        return None;
    };
    let anchor_locked = doc.child(shape, W10, "anchorlock").is_some();
    let rule = doc.attribute(shape, Some(O), "hr") == Some("t");
    let kind = if rule {
        InlineVmlKind::HorizontalRule
    } else if outlined(doc, shape) {
        InlineVmlKind::Outlined
    } else {
        InlineVmlKind::Plain
    };
    // The shape is drawn from the top left corner of its room, which can be larger.
    let InlineVml {
        drawn: (drawn_width, drawn_height),
        room: (width, height),
    } = reader.vml_sizes().inline((width, height), kind);
    let mut floating = Floating {
        width: drawn_width,
        height: drawn_height,
        look: Some(look(reader, shape, (drawn_width, drawn_height))),
        ..Floating::in_part(reader.part())
    };
    if let Some(flip) = reader.style_keyword(shape, style, "flip", FLIP) {
        floating.look = floating.look.take().map(|look| look.flipped(flip));
    }
    let quarters = quarter_turns_of(reader, shape, style);
    turn_drawing(&mut floating, quarters);
    text_box(reader, shape, &mut floating, quarters != 0);
    Some(Content::Drawing(Rc::new(InlineDrawing {
        width,
        height,
        left: Length::ZERO,
        top: Length::ZERO,
        shape: floating,
        drops: !rule,
        anchor_locked,
        extent: None,
    })))
}

/// Reads VML's `o:allowincell` attribute: defaults to [`crate::floating::CellLayout::InCell`]
/// unless explicitly `"f"`, `"false"`, or `"0"`.
pub(super) fn cell_layout(
    doc: &f_office_xml::Document,
    node: NodeId,
) -> crate::floating::CellLayout {
    let allowed = !matches!(
        doc.attribute(node, Some(O), "allowincell"),
        Some("f" | "F" | "false" | "FALSE" | "0")
    );
    crate::floating::CellLayout::of(allowed)
}

/// The values of `layout-flow` in the style of a VML text box (`v:textbox`, ECMA-376 Part 4,
/// 19.1.2.22): `horizontal` and `horizontal-ideographic` run across the box, and `vertical` and
/// `vertical-ideographic` turn the text, which F-Office lays out across the box with the warning
/// `turned-text-box-not-supported`. A missing value is `horizontal`.
const LAYOUT_FLOW: &Values<TextFlow> = &Values::new(&[
    own("horizontal", TextFlow::Across),
    own("horizontal-ideographic", TextFlow::Across),
    own("vertical", TextFlow::Turned),
    own("vertical-ideographic", TextFlow::Turned),
]);

/// Reads the text box of a shape (`v:textbox`): its insets and its content. A box whose text
/// is turned ([`LAYOUT_FLOW`]), or whose shape is rotated (`rotated`), is laid out across the box
/// upright, with one warning.
fn text_box(reader: &mut PartReader, shape: NodeId, floating: &mut Floating, rotated: bool) {
    let doc = reader.doc;
    if let Some(text_box) = doc.child(shape, V, "textbox") {
        floating.insets = insets(reader, text_box);
        floating.inset_edge = InsetEdge::Vml;
        floating.text_rect = text_rect(reader, shape);
        // Page numbers in a text box count like those around it.
        if let Some(content) = ns::text_box_content(doc, text_box) {
            floating.blocks = read_story(reader, content);
            // A turned text box is laid out across its box.
            let style = Style::new(doc.attribute(text_box, None, "style").unwrap_or(""));
            let flow = reader.style_keyword(text_box, &style, "layout-flow", LAYOUT_FLOW);
            if flow == Some(TextFlow::Turned) || rotated {
                reader.feature_not_supported(Feature::TurnedTextBox);
            }
        }
    }
}

/// The text rectangle of a `v:shape` of a shape type (`type`, the `id` of a `v:shapetype` of
/// the part): the first rectangle of the `textboxrect` of its path (`v:path`), the shape's own
/// path before its type's, evaluated with the type's formulas (`v:formulas`, the shape's own
/// before them) and adjust values (`adj`, each of the shape's in place of the type's), in the
/// coordinates of `coordsize`. `None` for a shape without a type or a rectangle, and for a
/// rectangle that does not evaluate, with the warning that the shape's geometry is not drawn.
fn text_rect(reader: &mut PartReader, shape: NodeId) -> Option<TextRect> {
    let doc = reader.doc;
    if !doc.is(shape, V, "shape") {
        return None;
    }
    let id = doc
        .attribute(shape, None, "type")?
        .trim()
        .trim_start_matches('#');
    let kind = reader.shape_type(id)?;
    let rect = path_attribute(doc, [shape, kind], "textboxrect")?;
    let evaluated = evaluate_text_rect(doc, shape, kind, rect);
    if evaluated.is_none() {
        reader.feature_not_supported(Feature::VmlGeometry);
    }
    evaluated
}

/// An attribute of the path (`v:path`) of the first of `nodes` whose path has it.
fn path_attribute<'d>(doc: &'d Document, nodes: [NodeId; 2], name: &str) -> Option<&'d str> {
    nodes.into_iter().find_map(|node| {
        doc.child(node, V, "path")
            .and_then(|path| doc.attribute(path, None, name))
    })
}

/// Two whole numbers split by `,`, such as `coordsize` or `limo`, or `None`.
fn pair(text: &str) -> Option<(i64, i64)> {
    match shape_type::numbers(text)?.as_slice() {
        [Some(across), Some(down)] => Some((*across, *down)),
        _ => None,
    }
}

/// The adjust values of the shape `shape` of the type `kind`: the type's (`adj`), each of the
/// shape's in place of the type's, a missing one 0, or `None` when one does not read.
fn adjust_values(doc: &Document, shape: NodeId, kind: NodeId) -> Option<Vec<i64>> {
    let adjust_of = |node: NodeId| match doc.attribute(node, None, "adj") {
        None => Some(Vec::new()),
        Some(text) => shape_type::numbers(text),
    };
    let mut adjust: Vec<i64> = adjust_of(kind)?
        .into_iter()
        .map(Option::unwrap_or_default)
        .collect();
    for (index, value) in adjust_of(shape)?.into_iter().enumerate() {
        if let Some(value) = value {
            if adjust.len() <= index {
                adjust.resize(index + 1, 0);
            }
            *adjust.get_mut(index)? = value;
        }
    }
    Some(adjust)
}

/// The formulas (`v:f eqn`) of the first of `nodes` that has `v:formulas`.
fn equations(doc: &Document, nodes: [NodeId; 2]) -> Vec<&str> {
    nodes
        .into_iter()
        .find_map(|node| doc.child(node, V, "formulas"))
        .map_or_else(Vec::new, |formulas| {
            doc.child_elements(formulas)
                .filter(|f| doc.is(*f, V, "f"))
                .filter_map(|f| doc.attribute(f, None, "eqn"))
                .collect()
        })
}

/// The text rectangle `rect` of the shape `shape` of the type `kind`, or `None` when a value
/// does not read or a formula does not evaluate ([`text_rect`]).
fn evaluate_text_rect(doc: &Document, shape: NodeId, kind: NodeId, rect: &str) -> Option<TextRect> {
    let adjust = adjust_values(doc, shape, kind)?;
    let size = match [shape, kind]
        .into_iter()
        .find_map(|node| doc.attribute(node, None, "coordsize"))
    {
        None => (shape_type::COORDINATES, shape_type::COORDINATES),
        Some(text) => pair(text)?,
    };
    let values = shape_type::formulas(&equations(doc, [shape, kind]), &adjust, size)?;
    let preset = doc
        .attribute(kind, Some(O), "spt")
        .and_then(|spt| spt.trim().parse().ok());
    let edges = shape_type::text_rect(preset, rect, &values, &adjust, size)?;
    let limo = match path_attribute(doc, [shape, kind], "limo") {
        None => None,
        Some(text) => Some(pair(text)?),
    };
    Some(TextRect { edges, size, limo })
}

/// The VML elements of a `w:pict` or `w:object` that F-Office does not read: an image element
/// (`v:image`) as a picture.
const UNREAD: [(&str, Drawing); 1] = [("image", Drawing::Picture)];

/// Keeps the warning that each element of [`UNREAD`] of a `w:pict` or `w:object` `node` is
/// left out ([`Reason::Unsupported`]).
fn skip_unread(reader: &mut PartReader, node: NodeId) {
    let doc = reader.doc;
    for child in doc.child_elements(node) {
        if let Some((_, drawing)) = UNREAD.iter().find(|(name, _)| doc.is(child, V, name)) {
            reader.drawing_skipped(*drawing, Reason::Unsupported);
        }
    }
}

/// The clockwise CSS `rotation` of a floating VML shape, in 60,000ths of a degree in
/// `0..FULL_TURN`, or 0 for a `v:textpath` (which reads its own rotation).
fn floating_rotation(
    reader: &mut PartReader,
    shape: NodeId,
    style: &Style,
    floating: &Floating,
) -> i64 {
    if floating.text_path.is_some() {
        return 0;
    }
    rotation_of(reader, shape, style)
}

/// Reads CSS `rotation` of `shape` in 60,000ths of a degree normalized into `0..FULL_TURN`.
fn rotation_of(reader: &mut PartReader, shape: NodeId, style: &Style) -> i64 {
    reader
        .style_value(shape, style, "rotation", css::angle)
        .unwrap_or(0)
        .rem_euclid(FULL_TURN)
}

/// Converts a VML CSS `rotation` and CSS `flip` (where Word rotates first and flips second) into
/// DrawingML's rotation angle (which flips first and rotates second).
fn vml_to_drawingml_rotation(rotation: i64, css_flip: [bool; 2]) -> i64 {
    let signed = if css_flip[0] ^ css_flip[1] {
        -rotation
    } else {
        rotation
    };
    signed.rem_euclid(FULL_TURN)
}

/// Applies arbitrary clockwise `rotation` and `flip` to a floating VML shape or picture.
/// Warns [`Feature::VmlRotation`] and draws upright only for cropped pictures at non-quarter
/// angles.
fn apply_floating_rotation(
    reader: &mut PartReader,
    floating: &mut Floating,
    raw_rotation: i64,
    css_flip: [bool; 2],
    picture_flip: [bool; 2],
) {
    let dml_rot = vml_to_drawingml_rotation(raw_rotation, css_flip);
    floating.look = floating.look.take().map(|look| look.turned(dml_rot));
    let Some(picture) = &mut floating.picture else {
        return;
    };
    if let Some(quarters) = quarter_turns(dml_rot) {
        picture.turn = turn(quarters, picture_flip);
    } else if picture.crop == Edges::default()
        && let Some(turned) = any_turn(dml_rot, picture_flip)
    {
        picture.turn = Some(turned);
    } else {
        reader.feature_not_supported(Feature::VmlRotation);
        picture.turn = turn(0, picture_flip);
    }
}

/// What a shape `shape` without a picture draws: its line of text ([`text_path`]) in place of
/// a shape where the target reads text paths, or else its shape's look.
fn drawn(
    reader: &mut PartReader,
    shape: NodeId,
    style: &Style,
    box_size: (Length, Length),
) -> (Option<ShapeLook>, Option<TextPath>) {
    // quirk: VmlTextPath::InkAligned (src/quirks.rs)
    let path = if reader.vml_sizes().reads_text_paths() {
        text_path(reader, shape, style)
    } else {
        None
    };
    match path {
        Some(path) => (None, Some(path)),
        None => (Some(look(reader, shape, box_size)), None),
    }
}

/// The line of text of a shape `shape` of the type 136 (plain text that fills the shape, as
/// Word writes a watermark) with a `v:textpath` that gives its `string` and the
/// `font-family` of its CSS style: the shape's `fillcolor` (white by default) mixed with white
/// by the `opacity` of its `v:fill`, and the `rotation` of the shape's CSS `style`. The text
/// path's own size, bold and italic, and the shape's line, are not read. Another shape gives
/// `None`.
fn text_path(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<TextPath> {
    let doc = reader.doc;
    let kind = doc.attribute(shape, None, "type")?.trim_start_matches('#');
    if kind != "_x0000_t136" {
        return None;
    }
    let path = doc.child(shape, V, "textpath")?;
    let string = doc.attribute(path, None, "string")?;
    let path_style = Style::new(doc.attribute(path, None, "style").unwrap_or(""));
    let face = path_style
        .get("font-family")?
        .trim()
        .trim_matches(['"', '\'']);
    let color = reader
        .or_missing_in(shape, (None, "fillcolor"), css::color)
        .unwrap_or(Rgb::WHITE);
    let opacity = doc
        .child(shape, V, "fill")
        .and_then(|fill| reader.or_missing_in(fill, (None, "opacity"), css::fraction))
        .map_or(Opacity::FULL, Opacity::clamped);
    let rotation = reader
        .style_value(shape, style, "rotation", css::angle)
        .unwrap_or(0);
    Some(TextPath {
        string: string.to_owned(),
        face: FamilyName::new(face),
        color: on_white(color, opacity),
        rotation,
    })
}

/// Reads a shape `shape` that floats: its place, size, wrap, look and text box, or its picture
/// (a `v:imagedata` that names an image, [`image_data`]), which fills its box and draws no line
/// or fill of the shape. A linked image gives `None` with a warning ([`embedded_image`]).
fn read_floating(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<Floating> {
    let doc = reader.doc;
    let embed = match image_data(doc, shape) {
        None => None,
        // F-Office does not draw the color effects of a picture, such as the washout of a
        // watermark, yet, and leaves such a picture out with a warning.
        Some(data) if changes_colors(doc, data) => {
            reader.drawing_skipped(Drawing::Picture, Reason::Unsupported);
            return None;
        }
        Some(data) => Some((embedded_image(reader, data, VML_IMAGE)?, data)),
    };
    let (width, height) = (size(style, "width"), size(style, "height"));
    let (box_width, box_height) = (
        width.unwrap_or(Length::ZERO),
        height.unwrap_or(Length::ZERO),
    );
    let point_shape = doc.is(shape, V, "polyline") || doc.is(shape, V, "curve");
    let (look, text_path) = if embed.is_some() || point_shape {
        (None, None)
    } else {
        drawn(reader, shape, style, (box_width, box_height))
    };
    let z_index = reader.style_value(shape, style, "z-index", css::number);
    let mut floating = Floating {
        h: across(reader, shape, style),
        v: position(reader, shape, style, &DOWN),
        width: box_width,
        height: box_height,
        behind: z_index.is_some_and(|z| z < 0),
        cell_layout: cell_layout(doc, shape),
        stack: z_index.map_or(0, i64::unsigned_abs),
        look,
        picture: embed.map(|(embed, data)| picture(reader, embed, data, box_width, box_height)),
        text_path,
        ..Floating::in_part(reader.part())
    };
    if !apply_floating_geometry(reader, shape, style, (width, height), &mut floating) {
        return None;
    }
    let css_flip = if doc.is(shape, V, "line") {
        [false; 2]
    } else if let Some(look) = &floating.look {
        look.flips()
    } else {
        reader
            .style_keyword(shape, style, "flip", FLIP)
            .unwrap_or([false; 2])
    };
    let rotation = floating_rotation(reader, shape, style, &floating);
    apply_floating_rotation(reader, &mut floating, rotation, css_flip, css_flip);
    floating.wrap = wrap(reader, shape, style);
    text_box(reader, shape, &mut floating, rotation != 0);
    let kind = doc
        .attribute(shape, None, "type")
        .and_then(|id| reader.shape_type(id.trim().trim_start_matches('#')));
    if let Some(shadow) = vml_shadow(reader, shape, kind) {
        let stroke = floating
            .look
            .as_ref()
            .and_then(|look| look.line(&ShapeTheme::default()))
            .map_or(Length::ZERO, |(_, _, width)| width);
        floating.vml_shadow = Some(shadow);
        floating.effect = vml_shadow_effect(shadow.offset, stroke);
    }
    Some(floating)
}

/// Applies bounding box and geometry overrides for `v:line`, `v:polyline`, `v:curve`, or CSS flip
/// onto `floating`, returning `false` when the shape cannot be placed.
fn apply_floating_geometry(
    reader: &mut PartReader,
    shape: NodeId,
    style: &Style,
    (width, height): (Option<Length>, Option<Length>),
    floating: &mut Floating,
) -> bool {
    let doc = reader.doc;
    if doc.is(shape, V, "line") {
        let Some(((x0, y0), (x1, y1))) =
            css_point(doc, shape, "from").zip(css_point(doc, shape, "to"))
        else {
            return false;
        };
        floating.h.offset = x0.min(x1);
        floating.v.offset = y0.min(y1);
        floating.width = x0.max(x1) - x0.min(x1);
        floating.height = y0.max(y1) - y0.min(y1);
        let flip = [x1 < x0, y1 < y0];
        floating.look = floating.look.take().map(|look| look.flipped(flip));
        return true;
    }
    if doc.is(shape, V, "polyline") || doc.is(shape, V, "curve") {
        let Some(placed) = floating_point_shape(doc, shape) else {
            reader.drawing_skipped(Drawing::Shape, Reason::Unsupported);
            return false;
        };
        floating.h.offset += placed.left;
        floating.v.offset += placed.top;
        floating.width = placed.width;
        floating.height = placed.height;
        let flip = reader
            .style_keyword(shape, style, "flip", FLIP)
            .unwrap_or([false; 2]);
        floating.look =
            Some(look_with_geometry(reader, shape, None, placed.geometry).flipped(flip));
        return true;
    }
    if width.is_none() || height.is_none() {
        let drawing = if floating.picture.is_some() {
            Drawing::Picture
        } else {
            Drawing::Shape
        };
        reader.drawing_skipped(drawing, Reason::Unsupported);
        return false;
    }
    if let Some(flip) = reader.style_keyword(shape, style, "flip", FLIP) {
        floating.look = floating.look.take().map(|look| look.flipped(flip));
    }
    true
}

/// The values of `flip` in the style of a straight connector, whether it is mirrored across and
/// down (ECMA-376 Part 4, 19.1.2.19: `x`, `y`, `xy` and `yx`), and `x y`, which Part 4 does not
/// list. Other text counts as missing (no flip) with a warning.
const FLIP: &Values<[bool; 2]> = &Values::new(&[
    own("x", [true, false]),
    own("y", [false, true]),
    own("xy", [true, true]),
    own("yx", [true, true]),
    // The two keywords with a space between them are both flips: Word draws the arrowhead at
    // the end of a diagonal connector with them at the top left end, where both flips put it.
    own("x y", [true, true]),
]);

/// The whole quarter turns, from 0 to 3, by which a VML shape or picture `shape` is turned
/// clockwise about the center of its box: the `rotation` of its CSS `style` (ECMA-376 Part 4,
/// 19.1.2.19), read once into DrawingML's unit ([`css::angle`]), as DrawingML turns a shape
/// ([`quarter_turns`]). F-Office draws another angle upright, with the warning
/// `vml-rotation-not-supported`, and a rotation that does not read counts as missing, no turn,
/// with `invalid-value`. The flips that F-Office draws, those of a straight connector, give the
/// same segment before or after a turn, and the box keeps its place and size.
fn quarter_turns_of(reader: &mut PartReader, shape: NodeId, style: &Style) -> i64 {
    let rotation = reader
        .style_value(shape, style, "rotation", css::angle)
        .unwrap_or(0);
    quarter_turns(rotation).unwrap_or_else(|| {
        reader.feature_not_supported(Feature::VmlRotation);
        0
    })
}

/// Turns the look or the picture of `floating` clockwise about the center of its box by
/// `quarters` whole quarter turns ([`quarter_turns_of`]); its box keeps its place and size.
fn turn_drawing(floating: &mut Floating, quarters: i64) {
    floating.look = floating
        .look
        .take()
        .map(|look| look.turned(quarters * QUARTER_TURN));
    if let Some(picture) = &mut floating.picture {
        picture.turn = turn(quarters, [false; 2]);
    }
}

/// Whether a `v:imagedata` changes the colors of its picture: its contrast (`gain`), its
/// brightness (`blacklevel`), or gray or black and white (`grayscale`, `bilevel`), as the
/// washout of a watermark does. ECMA-376 Part 4 defines these attributes of `v:imagedata`.
fn changes_colors(doc: &Document, data: NodeId) -> bool {
    let on = |name| matches!(doc.attribute(data, None, name), Some("t" | "true" | "1"));
    doc.attribute(data, None, "gain").is_some()
        || doc.attribute(data, None, "blacklevel").is_some()
        || on("grayscale")
        || on("bilevel")
}

/// The CSS properties of one axis of a VML shape's place, with the tables of their keywords.
struct Axis {
    /// What the place is measured from: `mso-position-horizontal-relative` or
    /// `mso-position-vertical-relative`.
    relative: (&'static str, &'static Values<Relative>),
    /// What a missing keyword of `relative` means: Part 4's default, `text` (19.1.2.19), the
    /// same place as the table's `text`.
    text: Relative,
    /// The alignment, which wins over the offset: `mso-position-horizontal` or
    /// `mso-position-vertical`.
    align: (&'static str, &'static Values<Option<Align>>),
    /// The offset: the first of the two that the style declares.
    offsets: [&'static str; 2],
}

/// The place across.
const ACROSS: Axis = Axis {
    relative: ("mso-position-horizontal-relative", RELATIVE_ACROSS),
    text: TEXT_ACROSS,
    align: ("mso-position-horizontal", ALIGN_ACROSS),
    offsets: ["margin-left", "left"],
};

/// The place down.
const DOWN: Axis = Axis {
    relative: ("mso-position-vertical-relative", RELATIVE_DOWN),
    text: TEXT_DOWN,
    align: ("mso-position-vertical", ALIGN_DOWN),
    offsets: ["margin-top", "top"],
};

/// Part 4's keyword `text` of both axes.
const TEXT: &str = "text";

/// Part 4's `text` across, the text column that holds the anchor, which a missing keyword also
/// means. F-Office draws it as the margins ([`across`]).
const TEXT_ACROSS: Relative = Relative::Column;

/// Part 4's `text` down, the anchor paragraph, which a missing keyword also means.
const TEXT_DOWN: Relative = Relative::Paragraph;

/// `mso-position-horizontal-relative`, what a VML shape's place across is measured from
/// (ECMA-376 Part 4, 19.1.2.19: `margin`, `page`, `text` and `char`), with the margin areas that
/// Word writes and Part 4 does not list. `text`, which a missing keyword also means, is the
/// text column that holds the anchor, which [`across`] draws as the margins. `char`, the
/// anchor's character, is drawn as the margins, and `inner-margin-area` and
/// `outer-margin-area` as the left and the right margin areas on every page, as `ALIGN_H` draws
/// `inside` and `outside`.
const RELATIVE_ACROSS: &Values<Relative> = &Values::new(&[
    own("margin", Relative::Area(PageArea::Margin)),
    own("page", Relative::Area(PageArea::Page)),
    own(TEXT, TEXT_ACROSS),
    another("char", Relative::Area(PageArea::Margin)),
    own("left-margin-area", Relative::Area(PageArea::StartMargin)),
    own("right-margin-area", Relative::Area(PageArea::EndMargin)),
    another("inner-margin-area", Relative::Area(PageArea::StartMargin)),
    another("outer-margin-area", Relative::Area(PageArea::EndMargin)),
]);

/// `mso-position-vertical-relative`, what a VML shape's place down is measured from (ECMA-376
/// Part 4, 19.1.2.19: `margin`, `page`, `text` and `line`), with the margin areas that Word
/// writes and Part 4 does not list. `text`, which a missing keyword also means, is the anchor
/// paragraph. `line`, the anchor's line, is drawn as the paragraph: no rendering has shown where
/// Word puts a VML shape placed from its line, where `relativeFrom="line"` of DrawingML counts
/// from the line on some targets (quirk `FromLine`). `inner-margin-area` and
/// `outer-margin-area` are drawn as the top and the bottom margin areas on every page. Other text, such as `paragraph`, counts as missing: the
/// paragraph.
const RELATIVE_DOWN: &Values<Relative> = &Values::new(&[
    own("margin", Relative::Area(PageArea::Margin)),
    own("page", Relative::Area(PageArea::Page)),
    own(TEXT, TEXT_DOWN),
    another("line", Relative::Paragraph),
    own("top-margin-area", Relative::Area(PageArea::StartMargin)),
    own("bottom-margin-area", Relative::Area(PageArea::EndMargin)),
    another("inner-margin-area", Relative::Area(PageArea::StartMargin)),
    another("outer-margin-area", Relative::Area(PageArea::EndMargin)),
]);

/// `mso-position-horizontal`, a VML shape's alignment across (ECMA-376 Part 4, 19.1.2.19):
/// `absolute` is no alignment, so that the shape lies at its offset, and `inside` is drawn at
/// the left and `outside` at the right on every page, as `ALIGN_H` draws them. A value of the
/// other axis, such as `bottom`, and other text count as missing: the offset.
const ALIGN_ACROSS: &Values<Option<Align>> = &Values::new(&[
    own("absolute", None),
    own("left", Some(Align::Start)),
    own("center", Some(Align::Center)),
    own("right", Some(Align::End)),
    own("inside", Some(Align::Inside)),
    own("outside", Some(Align::Outside)),
]);

/// `mso-position-vertical`, a VML shape's alignment down, as [`ALIGN_ACROSS`] reads the one
/// across: `absolute` is no alignment, and `inside` is drawn at the top and `outside` at the
/// bottom on every page.
const ALIGN_DOWN: &Values<Option<Align>> = &Values::new(&[
    own("absolute", None),
    own("top", Some(Align::Start)),
    own("center", Some(Align::Center)),
    own("bottom", Some(Align::End)),
    another("inside", Some(Align::Start)),
    another("outside", Some(Align::End)),
]);

/// One axis of the place of the shape `shape`, from its CSS `style`: what it is measured from,
/// its offset and its alignment, which wins over the offset. The keywords read through the
/// axis's tables in any case, and one that does not read counts as missing, with a warning.
fn position(reader: &mut PartReader, shape: NodeId, style: &Style, axis: &Axis) -> Position {
    let (property, table) = axis.relative;
    let from = reader
        .style_keyword(shape, style, property, table)
        .unwrap_or(axis.text);
    let (property, table) = axis.align;
    let align = reader
        .style_keyword(shape, style, property, table)
        .flatten();
    // The first offset that reads; one that does not read counts as missing, with a warning.
    let offset = axis
        .offsets
        .iter()
        .find_map(|name| reader.style_value(shape, style, name, css::length))
        .unwrap_or(Length::ZERO);
    Position {
        from,
        offset,
        align,
        share: None,
    }
}

/// The place across of the shape `shape` ([`position`]). F-Office draws Part 4's text column
/// ([`TEXT_ACROSS`]) as the margins, the same place except in a main-document section of more
/// than one column, outside a table cell, where the column that holds the anchor can be a
/// later one. It notes the shape, so that the body's reader warns there
/// ([`warn_text_column`]). No Word page shows such an anchor in a later column yet.
fn across(reader: &mut PartReader, shape: NodeId, style: &Style) -> Position {
    let mut place = position(reader, shape, style, &ACROSS);
    if place.from == TEXT_ACROSS {
        place.from = Relative::Area(PageArea::Margin);
        reader.note_text_column(shape);
    }
    place
}

/// Keeps the warning that F-Office draws Part 4's `text` across of the shape `shape`, which
/// [`across`] noted, as another value, the margins: for a shape that the body's reader finds
/// where the two places can differ.
pub(crate) fn warn_text_column(reader: &mut PartReader, shape: NodeId) {
    reader.not_supported(shape, style_place(ACROSS.relative.0), TEXT);
}

/// Emits the same text-column warning using an already-captured element name (used by the
/// streaming `<w:body>` reader after the single-block XML fragment has been dropped).
pub(crate) fn warn_text_column_named(reader: &mut PartReader, element: f_office_warnings::Name) {
    reader.not_supported_named(element, style_place(ACROSS.relative.0), TEXT);
}

/// How the text wraps around a VML shape, as the `type` of its `w10:wrap` names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WrapType {
    /// Beside the box, on the sides that the wrap's `side` names (`square`).
    Square,
    /// Beside the box, where a line takes the widest free piece (`tight`, `through`).
    Beside,
    /// Above and below the box (`topAndBottom`).
    TopAndBottom,
    /// No wrap: the text stays where it is (`none`).
    Off,
}

/// `ST_WrapType` of ECMA-376 Part 4, the kind of a VML wrap (`w10:wrap type`): each name is
/// drawn, and a missing name is no wrap.
const WRAP_TYPE: &Values<WrapType> = &Values::new(&[
    own("topAndBottom", WrapType::TopAndBottom),
    own("square", WrapType::Square),
    own("none", WrapType::Off),
    own("tight", WrapType::Beside),
    own("through", WrapType::Beside),
]);

/// `ST_WrapSide` of ECMA-376 Part 4, the sides of a square VML wrap (`w10:wrap side`): each
/// name is drawn, and a missing name is both sides.
const WRAP_SIDE: &Values<WrapSides> = &Values::new(&[
    own("both", WrapSides::Both),
    own("left", WrapSides::Left),
    own("right", WrapSides::Right),
    own("largest", WrapSides::Largest),
]);

/// Reads how text wraps around a shape (`w10:wrap`), with the distances of
/// `mso-wrap-distance-*`. Square, tight and through wraps flow the text beside the box, and a
/// square wrap on the sides that its `side` names (ECMA-376 Part 4, 14.3.6), both by default.
/// The part reader reads the `type` and the `side` through their tables, with a warning for
/// text outside the type.
fn wrap(reader: &mut PartReader, shape: NodeId, style: &Style) -> Option<Wrap> {
    let element = reader.doc.child(shape, W10, "wrap")?;
    // A distance that does not read takes its default, with a warning.
    let distance = |reader: &mut PartReader, side: &str, default: Length| {
        let property = format!("mso-wrap-distance-{side}");
        reader
            .style_value(shape, style, &property, css::length)
            .unwrap_or(default)
    };
    // A square wrap has no polygon; a tight or through wrap keeps the text out of the box, as
    // F-Office does not read its `wrapcoords`.
    let beside = |reader: &mut PartReader, sides, polygon| Wrap::Beside {
        distances: Edges {
            left: distance(reader, "left", VML_WRAP_DISTANCE),
            top: distance(reader, "top", Length::ZERO),
            right: distance(reader, "right", VML_WRAP_DISTANCE),
            bottom: distance(reader, "bottom", Length::ZERO),
        },
        sides,
        polygon,
    };
    // A wrap without a type, of none, or of text outside the type leaves the text where it is.
    match reader.enumeration_in(element, (None, "type"), WRAP_TYPE)? {
        WrapType::Square => {
            let sides = reader.enumeration_in(element, (None, "side"), WRAP_SIDE);
            Some(beside(reader, Some(sides.unwrap_or_default()), None))
        }
        WrapType::Beside => Some(beside(reader, None, Some(Edges::default()))),
        WrapType::TopAndBottom => Some(Wrap::TopAndBottom {
            above: distance(reader, "top", Length::ZERO),
            below: distance(reader, "bottom", Length::ZERO),
        }),
        WrapType::Off => None,
    }
}

/// The insets of a text box (`v:textbox inset`), which lists the left, top, right and bottom
/// ones. A missing value is 0.1 inch at the sides and 0.05 inch above and below (ECMA-376
/// Part 4, 14.1.2.22), and so is an empty one; a value that does not read takes the default
/// too, with a warning.
fn insets(reader: &mut PartReader, text_box: NodeId) -> Edges<Length> {
    let (side, top) = VML_TEXT_BOX_INSETS;
    let defaults = [side, top, side, top];
    let text = reader.doc.attribute(text_box, None, "inset").unwrap_or("");
    let mut values = text.split(',').map(str::trim);
    Edges::from(defaults.map(|default| match values.next() {
        None | Some("") => default,
        Some(value) => css::length(value).unwrap_or_else(|| {
            reader.invalid(text_box, attribute("inset"), ReadAs::Missing);
            default
        }),
    }))
}

/// Whether a VML boolean (`ST_TrueFalse`, ECMA-376 Part 4) that is on when it is missing stays
/// on: it is off only for `f`, `false` or `0`.
fn on_unless_off(value: Option<&str>) -> bool {
    !matches!(value, Some("f" | "false" | "0"))
}

/// How F-Office draws the fill of a VML shape of each fill type (`v:fill type`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FillType {
    /// One color, the shape's `fillcolor`.
    Solid,
}

/// The fill types of VML (`ST_FillType` of `v:fill type`, ECMA-376 Part 4). F-Office draws
/// each as a solid fill of the shape's `fillcolor`: a gradient, a radial gradient, a tile, a
/// pattern and a picture (`frame`) are drawn as another value, with a warning.
const FILL_TYPE: &Values<FillType> = &Values::new(&[
    own("solid", FillType::Solid),
    another("gradient", FillType::Solid),
    another("gradientRadial", FillType::Solid),
    another("tile", FillType::Solid),
    another("pattern", FillType::Solid),
    another("frame", FillType::Solid),
]);

/// Reads the geometry of a VML shape, warning on [`Feature::VmlGeometry`] for unsupported types
/// or unreadable custom paths.
fn vml_geometry(
    reader: &mut PartReader,
    shape: NodeId,
    kind: Option<NodeId>,
    box_size: (Length, Length),
) -> Geometry {
    let doc = reader.doc;
    if is_line(doc, shape) {
        return Geometry::Line;
    }
    if doc.is(shape, V, "rect") {
        return Geometry::Rect;
    }
    if doc.is(shape, V, "oval") {
        return Geometry::Ellipse;
    }
    if doc.is(shape, V, "roundrect") {
        // `arcsize` is the corner radius as a share of half the shorter side, 0.2 by default,
        // and when it does not read, with a warning.
        let arc = reader
            .or_missing_in(shape, (None, "arcsize"), css::fraction)
            .unwrap_or(VML_ARC_SIZE);
        return Geometry::RoundRect(arc / 2);
    }
    if doc.is(shape, V, "arc") {
        if let Some(custom) = arc_geometry(doc, shape) {
            return Geometry::Custom(custom);
        }
        reader.feature_not_supported(Feature::VmlGeometry);
        return Geometry::Rect;
    }
    shape_type_geometry(reader, shape, kind, box_size)
}

/// Builds a [`CustomGeometry`] for a VML `v:arc` from its `startangle` and `endangle` attributes.
fn arc_geometry(doc: &Document, shape: NodeId) -> Option<CustomGeometry> {
    let (start_fd, sweep_fd) = shape_type::arc_sweep(
        doc.attribute(shape, None, "startangle"),
        doc.attribute(shape, None, "endangle"),
    )?;
    let half = COORDINATES / 2;
    let steps = vec![LiteralStep::AngleEllipse {
        center: [half, half],
        radii: [half, half],
        start_fd,
        sweep_fd,
        move_to_start: true,
    }];
    CustomGeometry::from_literal_paths(vec![LiteralPath {
        size: [COORDINATES, COORDINATES],
        steps,
        filled: true,
        stroked: true,
    }])
}

/// Parses a VML CSS coordinate pair attribute `name` (default `"0,0"`).
fn css_point(doc: &Document, shape: NodeId, name: &str) -> Option<(Length, Length)> {
    let text = doc.attribute(shape, None, name).unwrap_or("0,0");
    let (x, y) = text.split_once(',').unwrap_or((text, "0"));
    Some((css::length(x.trim())?, css::length(y.trim())?))
}

/// A point-defined VML geometry (`v:polyline` or `v:curve`) with its bounding box.
pub(super) struct PlacedGeometry {
    pub(super) left: Length,
    pub(super) top: Length,
    pub(super) width: Length,
    pub(super) height: Length,
    pub(super) geometry: Geometry,
}

/// Normalized bounding box and coordinates in `0..=COORDINATES`.
struct NormalizedPoints {
    left: Length,
    top: Length,
    width: Length,
    height: Length,
    points: Vec<[i64; 2]>,
}

/// Parses a floating `v:polyline` or `v:curve` in CSS length units into its bounding box and
/// normalized [`Geometry`].
fn floating_point_shape(doc: &Document, shape: NodeId) -> Option<PlacedGeometry> {
    if doc.is(shape, V, "polyline") {
        let raw = doc.attribute(shape, None, "points")?;
        let mut tokens = raw
            .split(|c: char| c.is_ascii_whitespace() || c == ',')
            .filter(|t| !t.is_empty());
        let mut pts = Vec::new();
        while let Some(x) = tokens.next() {
            let y = tokens.next()?;
            pts.push((css::length(x)?, css::length(y)?));
        }
        return polyline_geometry(&pts);
    }
    let from = css_point(doc, shape, "from")?;
    let to = css_point(doc, shape, "to")?;
    let c1 = doc
        .attribute(shape, None, "control1")
        .map_or(Some(from), |_| css_point(doc, shape, "control1"))?;
    let c2 = doc
        .attribute(shape, None, "control2")
        .map_or(Some(to), |_| css_point(doc, shape, "control2"))?;
    curve_geometry([from, c1, c2, to])
}

/// Normalizes a slice of page-space points into `0..=COORDINATES`.
fn normalize_points(pts: &[(Length, Length)]) -> Option<NormalizedPoints> {
    let &(first_x, first_y) = pts.first()?;
    let (mut min_x, mut max_x) = (first_x, first_x);
    let (mut min_y, mut max_y) = (first_y, first_y);
    for &(x, y) in pts.iter().skip(1) {
        min_x = min_x.min(x);
        max_x = max_x.max(x);
        min_y = min_y.min(y);
        max_y = max_y.max(y);
    }
    let width = max_x - min_x;
    let height = max_y - min_y;
    let scale_coord = |value: Length, min: Length, span: Length| -> Option<i64> {
        if span.units() <= 0 {
            return Some(0);
        }
        let scaled = div_round_i128(
            i128::from((value - min).units()) * i128::from(COORDINATES),
            i128::from(span.units()),
        );
        i64::try_from(scaled).ok()
    };
    let points = pts
        .iter()
        .map(|&(x, y)| {
            Some([
                scale_coord(x, min_x, width)?,
                scale_coord(y, min_y, height)?,
            ])
        })
        .collect::<Option<Vec<_>>>()?;
    Some(NormalizedPoints {
        left: min_x,
        top: min_y,
        width,
        height,
        points,
    })
}

/// Builds the bounding box and open [`Geometry`] for a VML `v:polyline` from page-space points.
pub(super) fn polyline_geometry(pts: &[(Length, Length)]) -> Option<PlacedGeometry> {
    let norm = normalize_points(pts)?;
    let (&first, rest) = norm.points.split_first()?;
    if rest.is_empty() {
        return None;
    }
    let mut steps = Vec::with_capacity(norm.points.len());
    steps.push(LiteralStep::Move(first));
    steps.extend(rest.iter().copied().map(LiteralStep::Line));
    let custom = CustomGeometry::from_literal_paths(vec![LiteralPath {
        size: [COORDINATES, COORDINATES],
        steps,
        filled: true,
        stroked: true,
    }])?;
    Some(PlacedGeometry {
        left: norm.left,
        top: norm.top,
        width: norm.width,
        height: norm.height,
        geometry: Geometry::Custom(custom),
    })
}

/// Builds the bounding box and open [`Geometry`] for a VML `v:curve` from `[from, c1, c2, to]`.
pub(super) fn curve_geometry(pts: [(Length, Length); 4]) -> Option<PlacedGeometry> {
    let norm = normalize_points(&pts)?;
    let [from, c1, c2, to] = <[_; 4]>::try_from(norm.points).ok()?;
    let custom = CustomGeometry::from_literal_paths(vec![LiteralPath {
        size: [COORDINATES, COORDINATES],
        steps: vec![LiteralStep::Move(from), LiteralStep::Cubic([c1, c2, to])],
        filled: true,
        stroked: true,
    }])?;
    Some(PlacedGeometry {
        left: norm.left,
        top: norm.top,
        width: norm.width,
        height: norm.height,
        geometry: Geometry::Custom(custom),
    })
}

fn shape_type_geometry(
    reader: &mut PartReader,
    shape: NodeId,
    kind: Option<NodeId>,
    box_size: (Length, Length),
) -> Geometry {
    let doc = reader.doc;
    let type_id = doc
        .attribute(shape, None, "type")
        .map(|t| t.trim().trim_start_matches('#'));
    // A shape's own explicit `@path` / `<v:path v="..."/>` wins over its type.
    if vml_path_string(doc, shape).is_some() {
        if let Some(custom) = custom_path_geometry(doc, shape, kind, box_size) {
            return Geometry::Custom(custom);
        }
        reader.feature_not_supported(Feature::VmlGeometry);
        return Geometry::Rect;
    }
    // Keep plain rectangle and text-box types as `Geometry::Rect` even when a `v:shapetype`
    // repeats the rectangle path, preserving square rectangle joins.
    if matches!(type_id, None | Some("_x0000_t1" | "_x0000_t202")) {
        return Geometry::Rect;
    }
    // A `v:textpath` shape's `v:shapetype` path defines WordArt guide rails, not a drawn outline.
    let has_text_path = doc.child(shape, V, "textpath").is_some()
        || kind.is_some_and(|k| doc.child(k, V, "textpath").is_some());
    if !has_text_path && let Some(custom) = custom_path_geometry(doc, shape, kind, box_size) {
        return Geometry::Custom(custom);
    }
    // Built-in preset shape type IDs when no explicit `v:shapetype` path is present.
    let geometry = match type_id {
        Some("_x0000_t2") => Geometry::RoundRect(VML_ARC_SIZE / 2),
        Some("_x0000_t3") => Geometry::Ellipse,
        _ => Geometry::Other,
    };
    if matches!(geometry, Geometry::Other) {
        reader.feature_not_supported(Feature::VmlGeometry);
    }
    geometry
}

/// The geometry, fill and line of a VML shape. A shape is filled with white and drawn with a
/// black line 0.75 pt wide unless its attributes say otherwise (ECMA-376 Part 4, 14.1.2.19).
/// A shape of another outline, and a fill of another type than solid, warn in `reader`.
fn look(reader: &mut PartReader, shape: NodeId, box_size: (Length, Length)) -> ShapeLook {
    let doc = reader.doc;
    let kind = doc
        .attribute(shape, None, "type")
        .and_then(|id| reader.shape_type(id.trim().trim_start_matches('#')));
    let geometry = vml_geometry(reader, shape, kind, box_size);
    look_with_geometry(reader, shape, kind, geometry)
}

/// Builds the [`ShapeLook`] of `shape` (inheriting from `kind` if any) using a precomputed
/// [`Geometry`].
pub(super) fn look_with_geometry(
    reader: &mut PartReader,
    shape: NodeId,
    kind: Option<NodeId>,
    geometry: Geometry,
) -> ShapeLook {
    let doc = reader.doc;
    let nodes = [shape, kind.unwrap_or(shape)];
    let attribute = |name: &str| doc.attribute(shape, None, name);
    let inherited =
        |name: &str| attribute(name).or_else(|| kind.and_then(|k| doc.attribute(k, None, name)));
    let fill_child = doc.child(shape, V, "fill");
    let fill_on = on_unless_off(inherited("filled"))
        && on_unless_off(fill_child.and_then(|f| doc.attribute(f, None, "on")))
        && on_unless_off(path_attribute(doc, nodes, "fillok"));
    // The type of a fill that is drawn: each is drawn as a solid fill of `fillcolor`, and the
    // table warns of the others.
    let fill = fill_on.then(|| {
        let fill_type =
            fill_child.and_then(|fill| reader.enumeration_in(fill, (None, "type"), FILL_TYPE));
        match fill_type {
            Some(FillType::Solid) | None => reader
                .or_missing_in(shape, (None, "fillcolor"), css::color)
                .unwrap_or(Rgb::WHITE),
        }
    });
    // A `v:stroke` child gives the line's color and weight too, and wins over the shape's
    // attributes (ECMA-376 Part 4, 14.1.2.21). A color that does not read counts as missing,
    // with a warning.
    let stroke = doc.child(shape, V, "stroke");
    let stroke_attribute = |name: &str| stroke.and_then(|s| doc.attribute(s, None, name));
    let is_stroked = outlined(doc, shape)
        && on_unless_off(path_attribute(doc, nodes, "strokeok"))
        && (attribute("stroked").is_some()
            || stroke_attribute("on").is_some()
            || on_unless_off(kind.and_then(|k| doc.attribute(k, None, "stroked"))));
    let line = is_stroked.then(|| {
        let color = stroke
            .and_then(|stroke| reader.or_missing_in(stroke, (None, "color"), css::color))
            .or_else(|| reader.or_missing_in(shape, (None, "strokecolor"), css::color))
            .unwrap_or(Rgb::BLACK);
        let width = stroke_attribute("weight")
            .or_else(|| attribute("strokeweight"))
            .and_then(css::length)
            .unwrap_or(VML_STROKE_WEIGHT);
        (color, width)
    });
    ShapeLook::plain(geometry, fill, line)
}

/// Reads an active single drop shadow (`v:shadow`, ECMA-376 Part 4, 14.1.2.18) on `shape` (or
/// its `kind` shape type), returning `None` when absent, turned off (`on` defaults to false),
/// or of a non-single type.
fn vml_shadow(reader: &mut PartReader, shape: NodeId, kind: Option<NodeId>) -> Option<VmlShadow> {
    let doc = reader.doc;
    let shadow = doc
        .child(shape, V, "shadow")
        .or_else(|| kind.and_then(|k| doc.child(k, V, "shadow")))?;
    let on = doc.attribute(shadow, None, "on")?;
    if crate::on_off::vml_true_false(&on.trim().to_ascii_lowercase()) != Some(true) {
        return None;
    }
    if let Some(shadow_type) = doc.attribute(shadow, None, "type")
        && !shadow_type.trim().eq_ignore_ascii_case("single")
    {
        return None;
    }
    let offset = vml_shadow_offset(doc.attribute(shadow, None, "offset"));
    let [r, g, b] = VML_SHADOW_COLOR;
    let rgb = reader
        .or_missing_in(shadow, (None, "color"), css::color)
        .unwrap_or(Rgb { r, g, b });
    let opacity = reader
        .or_missing_in(shadow, (None, "opacity"), css::fraction)
        .map_or(Opacity::FULL, Opacity::clamped);
    Some(VmlShadow {
        offset,
        color: ShadowColor { rgb, opacity },
    })
}

/// Parses the `offset` attribute of a VML `v:shadow` (`"x,y"`, each defaulting to
/// [`VML_SHADOW_OFFSET`]).
fn vml_shadow_offset(text: Option<&str>) -> ShadowOffset {
    let Some(text) = text else {
        return ShadowOffset {
            across: VML_SHADOW_OFFSET,
            down: VML_SHADOW_OFFSET,
        };
    };
    let mut parts = text.split(',');
    let parse = |part: Option<&str>| {
        part.map(str::trim)
            .filter(|s| !s.is_empty())
            .and_then(css::length)
            .unwrap_or(VML_SHADOW_OFFSET)
    };
    ShadowOffset {
        across: parse(parts.next()),
        down: parse(parts.next()),
    }
}

/// Computes the outer effect extents of a floating VML shape with an active drop shadow of
/// `offset` and outline weight `stroke`.
fn vml_shadow_effect(offset: ShadowOffset, stroke: Length) -> Edges<Length> {
    let zero = Length::ZERO;
    let edge = |out: Length| {
        if stroke > VML_STROKE_WEIGHT {
            out.max(zero) + stroke.div_toward_zero(2)
        } else {
            out.max(zero).max(stroke)
        }
    };
    Edges {
        left: edge(-offset.across),
        top: edge(-offset.down),
        right: edge(offset.across),
        bottom: edge(offset.down),
    }
}

/// The explicit path string of `shape` (`@path` or `<v:path v="..."/>`), if present.
fn vml_path_string(doc: &Document, shape: NodeId) -> Option<&str> {
    doc.attribute(shape, None, "path").or_else(|| {
        doc.child(shape, V, "path")
            .and_then(|node| doc.attribute(node, None, "v"))
    })
}

/// Parses a VML shape's explicit path (`@path` or `<v:path v="..."/>`) or its `v:shapetype`'s
/// formula-driven path into a [`CustomGeometry`], applying any `v:path limo` stretch point.
fn custom_path_geometry(
    doc: &Document,
    shape: NodeId,
    kind: Option<NodeId>,
    box_size: (Length, Length),
) -> Option<CustomGeometry> {
    let nodes = [shape, kind.unwrap_or(shape)];
    let text =
        vml_path_string(doc, shape).or_else(|| kind.and_then(|k| vml_path_string(doc, k)))?;
    let origin = nodes
        .into_iter()
        .find_map(|node| doc.attribute(node, None, "coordorigin"))
        .map_or(Some((0, 0)), pair)?;
    let (cw, ch) = nodes
        .into_iter()
        .find_map(|node| doc.attribute(node, None, "coordsize"))
        .map_or(Some((COORDINATES, COORDINATES)), pair)?;
    let (values, adjust) = evaluate_shape_formulas(doc, shape, kind, (cw, ch))?;
    let parsed = vml_path::parse_with(text, origin, &values, &adjust)?;
    let limo = path_attribute(doc, nodes, "limo").and_then(pair);
    let stretch = LimoStretch::new((cw, ch), limo, box_size);
    let paths = parsed
        .into_iter()
        .map(|sub| LiteralPath {
            size: stretch.size,
            steps: sub
                .steps
                .into_iter()
                .map(|step| lower_vml_step(step, &stretch))
                .collect(),
            filled: sub.filled,
            stroked: sub.stroked,
        })
        .collect();
    CustomGeometry::from_literal_paths(paths)
}

fn evaluate_shape_formulas(
    doc: &Document,
    shape: NodeId,
    kind: Option<NodeId>,
    size: (i64, i64),
) -> Option<(Vec<i64>, Vec<i64>)> {
    let Some(kind) = kind else {
        let eqs = equations(doc, [shape, shape]);
        if eqs.is_empty() && doc.attribute(shape, None, "adj").is_none() {
            return Some((Vec::new(), Vec::new()));
        }
        let adjust = adjust_values(doc, shape, shape)?;
        let values = shape_type::formulas(&eqs, &adjust, size)?;
        return Some((values, adjust));
    };
    let adjust = adjust_values(doc, shape, kind)?;
    let eqs = equations(doc, [shape, kind]);
    let values = shape_type::formulas(&eqs, &adjust, size)?;
    Some((values, adjust))
}

/// Optional `v:path limo` stretch mapping from `[0..cw] x [0..ch]` to an aspect-matched space.
struct LimoStretch {
    size: [i64; 2],
    orig: [i64; 2],
    limo_x: Option<i64>,
    limo_y: Option<i64>,
}

impl LimoStretch {
    fn new((cw, ch): (i64, i64), limo: Option<(i64, i64)>, (w, h): (Length, Length)) -> Self {
        let plain = Self {
            size: [cw, ch],
            orig: [cw, ch],
            limo_x: None,
            limo_y: None,
        };
        let Some((lx, ly)) = limo else {
            return plain;
        };
        if cw <= 0 || ch <= 0 || w.units() <= 0 || h.units() <= 0 {
            return plain;
        }
        let wu = i128::from(w.units());
        let hu = i128::from(h.units());
        match (wu * i128::from(ch)).cmp(&(hu * i128::from(cw))) {
            std::cmp::Ordering::Greater => {
                let Some(sw) = i64::try_from(div_round_i128(i128::from(ch) * wu, hu))
                    .ok()
                    .filter(|&v| v > 0)
                else {
                    return plain;
                };
                Self {
                    size: [sw, ch],
                    orig: [cw, ch],
                    limo_x: Some(lx),
                    limo_y: None,
                }
            }
            std::cmp::Ordering::Less => {
                let Some(sh) = i64::try_from(div_round_i128(i128::from(cw) * hu, wu))
                    .ok()
                    .filter(|&v| v > 0)
                else {
                    return plain;
                };
                Self {
                    size: [cw, sh],
                    orig: [cw, ch],
                    limo_x: None,
                    limo_y: Some(ly),
                }
            }
            std::cmp::Ordering::Equal => plain,
        }
    }

    fn point(&self, [x, y]: [i64; 2]) -> [i64; 2] {
        let sx = match self.limo_x {
            Some(lx) if x > lx => self.size[0].saturating_sub(self.orig[0].saturating_sub(x)),
            _ => x,
        };
        let sy = match self.limo_y {
            Some(ly) if y > ly => self.size[1].saturating_sub(self.orig[1].saturating_sub(y)),
            _ => y,
        };
        [sx, sy]
    }
}

fn lower_vml_step(step: vml_path::Step, stretch: &LimoStretch) -> LiteralStep {
    match step {
        vml_path::Step::Move(p) => LiteralStep::Move(stretch.point(p)),
        vml_path::Step::Line(p) => LiteralStep::Line(stretch.point(p)),
        vml_path::Step::Cubic([c1, c2, p]) => {
            LiteralStep::Cubic([stretch.point(c1), stretch.point(c2), stretch.point(p)])
        }
        vml_path::Step::QuadX(p) => LiteralStep::QuadX(stretch.point(p)),
        vml_path::Step::QuadY(p) => LiteralStep::QuadY(stretch.point(p)),
        vml_path::Step::BoxArc {
            bounds: [l, t, r, b],
            start,
            end,
            clockwise,
            move_to_start,
        } => {
            let [nl, nt] = stretch.point([l, t]);
            let [nr, nb] = stretch.point([r, b]);
            LiteralStep::BoxArc {
                bounds: [nl, nt, nr, nb],
                start: stretch.point(start),
                end: stretch.point(end),
                clockwise,
                move_to_start,
            }
        }
        vml_path::Step::AngleEllipse {
            center: [cx, cy],
            radii: [rx, ry],
            start_fd,
            sweep_fd,
            move_to_start,
        } => {
            let [nl, nt] = stretch.point([cx - rx, cy - ry]);
            let [nr, nb] = stretch.point([cx + rx, cy + ry]);
            LiteralStep::AngleEllipse {
                center: [i64::midpoint(nl, nr), i64::midpoint(nt, nb)],
                radii: [(nr - nl).abs() / 2, (nb - nt).abs() / 2],
                start_fd,
                sweep_fd,
                move_to_start,
            }
        }
        vml_path::Step::Close => LiteralStep::Close,
    }
}

/// Whether a VML shape has a line: its `stroked` is on, and so is the `on` of its `v:stroke`
/// child, which wins over the shape's attributes (ECMA-376 Part 4, 14.1.2.21); each is on when
/// it is missing.
fn outlined(doc: &Document, shape: NodeId) -> bool {
    let stroke_on = doc
        .child(shape, V, "stroke")
        .and_then(|stroke| doc.attribute(stroke, None, "on"));
    on_unless_off(doc.attribute(shape, None, "stroked")) && on_unless_off(stroke_on)
}

#[cfg(test)]
mod tests;