f-office-docx 0.1.0

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
//! VML (`w:pict` and `w:object`), the older drawing markup of ECMA-376 Part 4: pictures in
//! their text line, and floating shapes and text boxes.

use std::rc::Rc;

use f_office_drawingml::color::on_white;
use f_office_drawingml::shape::{Geometry, ShapeLook, quarter_turns};
use f_office_fonts::FamilyName;
use f_office_paint::{Opacity, Rgb};
use f_office_units::scale::QUARTER_TURN;
use f_office_units::{Edges, Length};
use f_office_vml::css::{self, Style};
use f_office_vml::shape_type::{self, 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, Wrap, WrapSides,
};
use crate::ns::{self, O, R, V, W, W10};
use crate::params::{VML_ARC_SIZE, VML_STROKE_WEIGHT, VML_TEXT_BOX_INSETS, VML_WRAP_DISTANCE};
use crate::picture::{Picture, VML_IMAGE, 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. A group of shapes (`v:group`), a polyline, an arc, a
/// curve and an image element (`v:image`) are left out, each with a warning ([`UNREAD`]), and a
/// shape inside a group is not read. 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| 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
    };
    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; 5] = ["shape", "rect", "roundrect", "oval", "line"];

/// 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)),
        ..Floating::in_part(reader.part())
    };
    let quarters = quarter_turns_of(reader, shape, style);
    turn_drawing(&mut floating, quarters);
    text_box(reader, shape, &mut floating, quarters);
    Some(Content::Drawing(Rc::new(InlineDrawing {
        width,
        height,
        left: Length::ZERO,
        top: Length::ZERO,
        shape: floating,
        drops: !rule,
        anchor_locked,
        extent: None,
    })))
}

/// 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 turned by `quarters` quarter turns other
/// than none ([`quarter_turns_of`]), is laid out across the box upright, with one warning.
fn text_box(reader: &mut PartReader, shape: NodeId, floating: &mut Floating, quarters: i64) {
    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) || quarters != 0 {
                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, each with the
/// kind of drawing that it leaves out: a group of shapes (`v:group`), a polyline, an arc and a
/// curve as a shape, and an image element (`v:image`) as a picture.
const UNREAD: [(&str, Drawing); 5] = [
    ("group", Drawing::Shape),
    ("polyline", Drawing::Shape),
    ("arc", Drawing::Shape),
    ("curve", Drawing::Shape),
    ("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 whole quarter turns of a floating shape `shape` ([`quarter_turns_of`]), or 0 for a line
/// of text that fills its box, which turns by its own angle as its layout reads it.
fn turns(reader: &mut PartReader, shape: NodeId, style: &Style, floating: &Floating) -> i64 {
    if floating.text_path.is_some() {
        return 0;
    }
    quarter_turns_of(reader, shape, style)
}

/// 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,
) -> (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)), 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 (look, text_path) = embed
        .as_ref()
        .map_or_else(|| drawn(reader, shape, style), |_| (None, None));
    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 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),
        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())
    };
    // A line (`v:line`) runs between its `from` and `to` points, measured from the place that
    // `mso-position-*-relative` names, and its box is the box of the two points.
    if doc.is(shape, V, "line") {
        let point = |name| {
            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())?))
        };
        let ((x0, y0), (x1, y1)) = (point("from")?, point("to")?);
        floating.h.offset = x0.min(x1);
        floating.v.offset = y0.min(y1);
        // The CSS reader keeps each point within `Length::FILE_LIMIT`, so the sizes fit.
        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));
    } else if width.is_none() || height.is_none() {
        // A shape or picture without a CSS width or height, other than a line, is left out.
        let drawing = if floating.picture.is_some() {
            Drawing::Picture
        } else {
            Drawing::Shape
        };
        reader.drawing_skipped(drawing, Reason::Unsupported);
        return None;
    } else if is_line(doc, shape) {
        // A straight connector mirrors itself with `flip` in its style.
        let flip = reader
            .style_keyword(shape, style, "flip", FLIP)
            .unwrap_or_default();
        floating.look = floating.look.take().map(|look| look.flipped(flip));
    }
    let quarters = turns(reader, shape, style, &floating);
    turn_drawing(&mut floating, quarters);
    floating.wrap = wrap(reader, shape, style);
    text_box(reader, shape, &mut floating, quarters);
    Some(floating)
}

/// 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)),
    another("inside", Some(Align::Start)),
    another("outside", Some(Align::End)),
]);

/// `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);
}

/// 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),
]);

/// 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) -> ShapeLook {
    let doc = reader.doc;
    let attribute = |name: &str| doc.attribute(shape, None, name);
    let on = |name: &str| on_unless_off(attribute(name));
    let geometry = if is_line(doc, shape) {
        Geometry::Line
    } else if doc.is(shape, V, "rect") {
        Geometry::Rect
    } else if doc.is(shape, V, "oval") {
        Geometry::Ellipse
    } else 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);
        Geometry::RoundRect(arc / 2)
    } else {
        // A shape of the text box type (`#_x0000_t202`) or of no type is a rectangle.
        let geometry = match attribute("type").map(|t| t.trim_start_matches('#')) {
            None | Some("_x0000_t202" | "_x0000_t1") => Geometry::Rect,
            Some(_) => Geometry::Other,
        };
        // A shape of another type is not drawn, and one with its own path is drawn as a
        // rectangle.
        if matches!(geometry, Geometry::Other) || attribute("path").is_some() {
            reader.feature_not_supported(Feature::VmlGeometry);
        }
        geometry
    };
    // 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 = on("filled").then(|| {
        let fill_type = doc
            .child(shape, V, "fill")
            .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 line = outlined(doc, shape).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)
}

/// 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;