dxpdf 0.4.0

A fast DOCX-to-PDF converter powered by Skia
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
//! VML (Vector Markup Language) types — legacy shapes, paths, formulas, styling.

use super::content::Block;
use super::identifiers::{RelId, VmlShapeId};

/// §17.3.3.19: VML picture container. Wraps legacy VML shape content.
///
/// The `<w:pict>` element admits any of the VML primitive shape
/// elements (§14.1.2): `<v:shape>`, `<v:rect>`, `<v:roundrect>`,
/// `<v:oval>`, `<v:line>`, `<v:polyline>`, `<v:arc>`, `<v:curve>`,
/// `<v:image>`, `<v:group>`. We model the choice as a tagged enum
/// (`VmlPrimitive`) so each variant carries its element-specific
/// shape, while sharing common style/fill/stroke/etc. via
/// `VmlCommonAttrs`.
#[derive(Clone, Debug)]
pub struct Pict {
    /// VML §14.1.2.20: optional reusable shape type definition.
    pub shape_type: Option<VmlShapeType>,
    /// VML §14.1.2.* — primitive shape children in document order.
    pub primitives: Vec<VmlPrimitive>,
}

impl Pict {
    /// Convenience accessor: yields every `VmlShape` (the generic
    /// `<v:shape>` variant). Other primitive variants are skipped.
    /// Use this where the caller only handles `<v:shape>` today —
    /// new code should match on `VmlPrimitive` directly.
    pub fn shapes(&self) -> impl Iterator<Item = &VmlShape> {
        self.primitives.iter().filter_map(|p| match p {
            VmlPrimitive::Shape(s) => Some(s),
            _ => None,
        })
    }

    /// Mutable counterpart to [`Pict::shapes`].
    pub fn shapes_mut(&mut self) -> impl Iterator<Item = &mut VmlShape> {
        self.primitives.iter_mut().filter_map(|p| match p {
            VmlPrimitive::Shape(s) => Some(s),
            _ => None,
        })
    }
}

/// VML §14.1.2 — every primitive shape child of `<w:pict>`. Variants
/// share a `VmlCommonAttrs` payload accessed via [`VmlPrimitive::common`].
#[derive(Clone, Debug)]
pub enum VmlPrimitive {
    /// `<v:shape>` — generic shape with shapetype reference or own path.
    Shape(VmlShape),
    /// `<v:rect>` (§14.1.2.16) — bounding-box rectangle.
    Rect(VmlRect),
    /// `<v:roundrect>` (§14.1.2.17) — `@arcsize` corner radius.
    RoundRect(VmlRoundRect),
    /// `<v:oval>` (§14.1.2.13).
    Oval(VmlOval),
    /// `<v:line>` (§14.1.2.12) — `@from`/`@to` endpoints.
    Line(VmlLine),
    /// `<v:polyline>` (§14.1.2.15) — `@points` list.
    PolyLine(VmlPolyLine),
    /// `<v:arc>` (§14.1.2.3) — `@startangle`/`@endangle`.
    Arc(VmlArc),
    /// `<v:curve>` (§14.1.2.7) — Bezier with two control points.
    Curve(VmlCurve),
    /// `<v:image>` (§14.1.2.10) — image element with `@src`.
    Image(VmlImage),
    /// `<v:group>` (§14.1.2.9) — recursive shape grouping with its
    /// own coordinate system.
    Group(Box<VmlGroup>),
}

impl VmlPrimitive {
    /// Borrow the common attribute set every variant carries.
    pub fn common(&self) -> &VmlCommonAttrs {
        match self {
            VmlPrimitive::Shape(s) => &s.common,
            VmlPrimitive::Rect(r) => &r.common,
            VmlPrimitive::RoundRect(r) => &r.common,
            VmlPrimitive::Oval(o) => &o.common,
            VmlPrimitive::Line(l) => &l.common,
            VmlPrimitive::PolyLine(p) => &p.common,
            VmlPrimitive::Arc(a) => &a.common,
            VmlPrimitive::Curve(c) => &c.common,
            VmlPrimitive::Image(i) => &i.common,
            VmlPrimitive::Group(g) => &g.common,
        }
    }

    /// Mutable counterpart to [`VmlPrimitive::common`].
    pub fn common_mut(&mut self) -> &mut VmlCommonAttrs {
        match self {
            VmlPrimitive::Shape(s) => &mut s.common,
            VmlPrimitive::Rect(r) => &mut r.common,
            VmlPrimitive::RoundRect(r) => &mut r.common,
            VmlPrimitive::Oval(o) => &mut o.common,
            VmlPrimitive::Line(l) => &mut l.common,
            VmlPrimitive::PolyLine(p) => &mut p.common,
            VmlPrimitive::Arc(a) => &mut a.common,
            VmlPrimitive::Curve(c) => &mut c.common,
            VmlPrimitive::Image(i) => &mut i.common,
            VmlPrimitive::Group(g) => &mut g.common,
        }
    }
}

/// VML §14.1.2.18 CoreAttributes plus the shared child elements every
/// primitive admits: `<v:fill>`, `<v:stroke>`, `<v:textbox>`,
/// `<v:wrap>`, `<v:imagedata>`. Extracting these out of `VmlShape`
/// lets every other primitive type share the same parse-and-render
/// machinery without copying ten fields.
#[derive(Clone, Debug, Default)]
pub struct VmlCommonAttrs {
    /// Shape identifier.
    pub id: Option<VmlShapeId>,
    /// Parsed CSS2 style properties.
    pub style: VmlStyle,
    /// `@fillcolor` attribute fill color.
    pub fill_color: Option<VmlColor>,
    /// Whether the shape has a stroke.
    pub stroked: Option<bool>,
    /// VML §14.1.2.21: stroke child element.
    pub stroke: Option<VmlStroke>,
    /// VML §14.1.2.22: text box child element.
    pub text_box: Option<VmlTextBox>,
    /// VML §14.1.2.23: text wrapping around shape.
    pub wrap: Option<VmlWrap>,
    /// VML §14.1.2.11: image data reference.
    pub image_data: Option<VmlImageData>,
    /// VML §14.1.2.5 `<v:fill>` — fill child element. When present,
    /// overrides the `@fillcolor` attribute. Carries gradient/pattern/
    /// image fill specifications that the attribute can't express.
    pub fill: Option<VmlFill>,
}

/// VML §14.1.2.5 `<v:fill>` — fill specification on any shape.
///
/// The element carries many attributes; we model the most-used
/// subset and grow on demand. Non-solid fills (gradient/tile/pattern/
/// frame) are modeled but only `Solid` is renderered today; the
/// renderer falls through with a one-time `log::warn!` for the rest.
#[derive(Clone, Debug, Default)]
pub struct VmlFill {
    /// `@type` — fill kind. Defaults to `Solid` when omitted (matches
    /// spec).
    pub fill_type: VmlFillType,
    /// `@color` — primary color (used by Solid and most gradient
    /// types as the start color).
    pub color: Option<VmlColor>,
    /// `@color2` — secondary color (gradient end / pattern bg).
    pub color2: Option<VmlColor>,
    /// `@opacity` — 0..1; missing means opaque.
    pub opacity: Option<f32>,
    /// `@src` — relative path to a fill image (Tile/Frame).
    pub src: Option<String>,
    /// `r:id` — relationship-ID alternative to `@src` for fill image.
    pub rel_id: Option<RelId>,
}

/// VML §14.1.2.5 `@type` values. The spec also defines
/// `gradientCenter` and `gradientUnscaled`, which we treat as
/// gradient kinds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum VmlFillType {
    /// Solid color (default).
    #[default]
    Solid,
    /// Linear/axial gradient.
    Gradient,
    /// Radial gradient.
    GradientRadial,
    /// Tiled image fill.
    Tile,
    /// Frame (single-image) fill.
    Frame,
    /// Pattern fill with foreground/background colors.
    Pattern,
}

/// VML §14.1.2.16 `<v:rect>` — bounding-box rectangle.
#[derive(Clone, Debug)]
pub struct VmlRect {
    pub common: VmlCommonAttrs,
}

/// VML §14.1.2.17 `<v:roundrect>` — rectangle with rounded corners.
#[derive(Clone, Debug)]
pub struct VmlRoundRect {
    pub common: VmlCommonAttrs,
    /// `@arcsize` — corner radius as fraction of the smaller half-side.
    /// Stored as 0..=1; the spec admits values up to 0.5 in practice
    /// but Word emits up to 1.0.
    pub arcsize: Option<f32>,
}

/// VML §14.1.2.13 `<v:oval>`.
#[derive(Clone, Debug)]
pub struct VmlOval {
    pub common: VmlCommonAttrs,
}

/// VML §14.1.2.12 `<v:line>` — single segment between two points.
#[derive(Clone, Debug)]
pub struct VmlLine {
    pub common: VmlCommonAttrs,
    pub from: Option<VmlPoint>,
    pub to: Option<VmlPoint>,
}

/// VML §14.1.2.15 `<v:polyline>`.
#[derive(Clone, Debug)]
pub struct VmlPolyLine {
    pub common: VmlCommonAttrs,
    pub points: Vec<VmlPoint>,
}

/// VML §14.1.2.3 `<v:arc>`.
#[derive(Clone, Debug)]
pub struct VmlArc {
    pub common: VmlCommonAttrs,
    pub start_angle: Option<f32>,
    pub end_angle: Option<f32>,
}

/// VML §14.1.2.7 `<v:curve>` — cubic Bezier from `from` to `to` with
/// two control points.
#[derive(Clone, Debug)]
pub struct VmlCurve {
    pub common: VmlCommonAttrs,
    pub from: Option<VmlPoint>,
    pub control1: Option<VmlPoint>,
    pub control2: Option<VmlPoint>,
    pub to: Option<VmlPoint>,
}

/// VML §14.1.2.10 `<v:image>` — image element with `@src` attribute.
/// Distinct from `<v:shape>`+`<v:imagedata>` even though the rendering
/// outcome can be identical.
#[derive(Clone, Debug)]
pub struct VmlImage {
    pub common: VmlCommonAttrs,
    /// `@src` — file path or URL of the image.
    pub src: Option<String>,
}

/// VML §14.1.2.9 `<v:group>` — nested primitives with their own
/// coordinate system.
#[derive(Clone, Debug)]
pub struct VmlGroup {
    pub common: VmlCommonAttrs,
    /// Coordinate space declared by the group (`@coordsize`).
    pub coord_size: Option<VmlVector2D>,
    /// Origin of the group's coord space (`@coordorigin`).
    pub coord_origin: Option<VmlVector2D>,
    /// Child primitives in the group's coordinate system.
    pub children: Vec<VmlPrimitive>,
}

/// VML 2D point — typically `(x,y)` in the parent coord space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VmlPoint {
    pub x: f32,
    pub y: f32,
}

// ── Path Commands ────────────────────────────────────────────────────────────

/// VML §14.2.1.6: path coordinate — literal integer or `@n` formula reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlPathCoord {
    /// Literal integer coordinate value.
    Literal(i64),
    /// `@n` — reference to formula result n.
    FormulaRef(u32),
}

/// VML §14.2.1.6: a single path command in the shape path language.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlPathCommand {
    /// `m x,y` — move to absolute position.
    MoveTo { x: VmlPathCoord, y: VmlPathCoord },
    /// `l x,y` — line to absolute position.
    LineTo { x: VmlPathCoord, y: VmlPathCoord },
    /// `c x1,y1,x2,y2,x,y` — cubic bezier to absolute position.
    CurveTo {
        x1: VmlPathCoord,
        y1: VmlPathCoord,
        x2: VmlPathCoord,
        y2: VmlPathCoord,
        x: VmlPathCoord,
        y: VmlPathCoord,
    },
    /// `r dx,dy` — relative line to.
    RLineTo { dx: VmlPathCoord, dy: VmlPathCoord },
    /// `v dx1,dy1,dx2,dy2,dx,dy` — relative cubic bezier.
    RCurveTo {
        dx1: VmlPathCoord,
        dy1: VmlPathCoord,
        dx2: VmlPathCoord,
        dy2: VmlPathCoord,
        dx: VmlPathCoord,
        dy: VmlPathCoord,
    },
    /// `t dx,dy` — relative move to.
    RMoveTo { dx: VmlPathCoord, dy: VmlPathCoord },
    /// `x` — close subpath.
    Close,
    /// `e` — end of path.
    End,
    /// `qx x,y` — elliptical quadrant, x-axis first.
    QuadrantX { x: VmlPathCoord, y: VmlPathCoord },
    /// `qy x,y` — elliptical quadrant, y-axis first.
    QuadrantY { x: VmlPathCoord, y: VmlPathCoord },
    /// `nf` — no fill for following subpath.
    NoFill,
    /// `ns` — no stroke for following subpath.
    NoStroke,
    /// `wa/wr/at/ar x1,y1,x2,y2,x3,y3,x4,y4` — arc commands.
    Arc {
        /// `wa` (angle clockwise), `wr` (angle counter-clockwise),
        /// `at` (to clockwise), `ar` (to counter-clockwise).
        kind: VmlArcKind,
        bounding_x1: VmlPathCoord,
        bounding_y1: VmlPathCoord,
        bounding_x2: VmlPathCoord,
        bounding_y2: VmlPathCoord,
        start_x: VmlPathCoord,
        start_y: VmlPathCoord,
        end_x: VmlPathCoord,
        end_y: VmlPathCoord,
    },
}

/// VML §14.2.1.6: arc sub-type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlArcKind {
    /// `wa` — clockwise arc (angle).
    WA,
    /// `wr` — counter-clockwise arc (angle).
    WR,
    /// `at` — clockwise arc (to point).
    AT,
    /// `ar` — counter-clockwise arc (to point).
    AR,
}

// ── Formulas ─────────────────────────────────────────────────────────────────

/// VML §14.1.2.6: a single formula equation (`v:f eqn="..."`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VmlFormula {
    pub operation: VmlFormulaOp,
    pub args: [VmlFormulaArg; 3],
}

/// VML §14.1.2.6: formula operations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlFormulaOp {
    /// `val` — returns arg1.
    Val,
    /// `sum` — arg1 + arg2 - arg3.
    Sum,
    /// `product` — arg1 * arg2 / arg3.
    Product,
    /// `mid` — (arg1 + arg2) / 2.
    Mid,
    /// `abs` — |arg1|.
    Abs,
    /// `min` — min(arg1, arg2).
    Min,
    /// `max` — max(arg1, arg2).
    Max,
    /// `if` — if arg1 > 0 then arg2 else arg3.
    If,
    /// `sqrt` — sqrt(arg1).
    Sqrt,
    /// `mod` — sqrt(arg1² + arg2² + arg3²).
    Mod,
    /// `sin` — arg1 * sin(arg2).
    Sin,
    /// `cos` — arg1 * cos(arg2).
    Cos,
    /// `tan` — arg1 * tan(arg2).
    Tan,
    /// `atan2` — atan2(arg1, arg2) in fd units.
    Atan2,
    /// `sinatan2` — arg1 * sin(atan2(arg2, arg3)).
    SinAtan2,
    /// `cosatan2` — arg1 * cos(atan2(arg2, arg3)).
    CosAtan2,
    /// `sumangle` — arg1 + arg2 * 2^16 - arg3 * 2^16 (angle arithmetic).
    SumAngle,
    /// `ellipse` — arg3 * sqrt(1 - (arg1/arg2)²).
    Ellipse,
}

/// VML §14.1.2.6: formula argument — a reference or literal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlFormulaArg {
    /// Integer literal.
    Literal(i64),
    /// `#n` — adjustment value reference.
    AdjRef(u32),
    /// `@n` — formula result reference.
    FormulaRef(u32),
    /// Named guide value (width, height, xcenter, ycenter, etc.).
    Guide(VmlGuide),
}

/// VML §14.1.2.6: named guide constants available in formulas.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlGuide {
    Width,
    Height,
    XCenter,
    YCenter,
    XRange,
    YRange,
    PixelWidth,
    PixelHeight,
    PixelLineWidth,
    EmuWidth,
    EmuHeight,
    EmuWidth2,
    EmuHeight2,
}

// ── Shape Types and Shapes ───────────────────────────────────────────────────

/// VML Vector2D — unitless coordinate pair (e.g., coordsize="21600,21600").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VmlVector2D {
    pub x: i64,
    pub y: i64,
}

/// VML §14.1.2.20: shape type definition (reusable template for shapes).
#[derive(Clone, Debug)]
pub struct VmlShapeType {
    /// Shape type identifier (e.g., "_x0000_t202").
    pub id: Option<VmlShapeId>,
    /// Coordinate space for the shape (VML Vector2D, e.g., 21600,21600).
    pub coord_size: Option<VmlVector2D>,
    /// o:spt — shape type number (Office extension, xsd:float).
    pub spt: Option<f32>,
    /// Adjustment values for parameterized shapes (comma-separated integers).
    pub adj: Vec<i64>,
    /// VML §14.2.1.6: parsed shape path commands.
    pub path: Vec<VmlPathCommand>,
    /// Whether the shape is filled by default.
    pub filled: Option<bool>,
    /// Whether the shape is stroked by default.
    pub stroked: Option<bool>,
    /// VML §14.1.2.21: stroke child element.
    pub stroke: Option<VmlStroke>,
    /// VML §14.1.2.14: path child element.
    pub vml_path: Option<VmlPath>,
    /// VML §14.1.2.6: formula definitions.
    pub formulas: Vec<VmlFormula>,
    /// Office VML extension: editing locks.
    pub lock: Option<VmlLock>,
}

/// VML §14.1.2.19 `<v:shape>` — generic shape instance, optionally
/// referencing a `<v:shapetype>` and/or carrying its own path.
/// Common attribute and child elements live on
/// [`VmlCommonAttrs`]; only shape-specific fields stay here.
#[derive(Clone, Debug)]
pub struct VmlShape {
    /// Common attribute group + shared children.
    pub common: VmlCommonAttrs,
    /// `@type` — reference to a shapetype id (e.g., "#_x0000_t202").
    pub shape_type_ref: Option<VmlShapeId>,
    /// VML §14.1.2.14 `<v:path>` — explicit path child element.
    pub vml_path: Option<VmlPath>,
}

// ── Wrapping ─────────────────────────────────────────────────────────────────

/// VML §14.1.2.23: text wrapping element.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VmlWrap {
    /// Wrapping type.
    pub wrap_type: Option<VmlWrapType>,
    /// Which side(s) text wraps on.
    pub side: Option<VmlWrapSide>,
}

/// VML §14.1.2.23: wrap type values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlWrapType {
    TopAndBottom,
    Square,
    None,
    Tight,
    Through,
}

/// VML §14.1.2.23: wrap side values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlWrapSide {
    Both,
    Left,
    Right,
    Largest,
}

// ── Lock / Extension ─────────────────────────────────────────────────────────

/// Office VML extension: editing locks on a shape type or shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VmlLock {
    /// Lock aspect ratio.
    pub aspect_ratio: Option<bool>,
    /// v:ext — extension handling mode.
    pub ext: Option<VmlExtHandling>,
}

/// VML v:ext — extension handling mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlExtHandling {
    Edit,
    View,
    BackwardCompatible,
}

// ── Image Data ───────────────────────────────────────────────────────────────

/// VML §14.1.2.11: image data reference.
#[derive(Clone, Debug)]
pub struct VmlImageData {
    /// r:id — relationship ID to the image part.
    pub rel_id: Option<RelId>,
    /// o:title — image title/alt text.
    pub title: Option<String>,
}

// ── VML Style ────────────────────────────────────────────────────────────────

/// VML style — parsed CSS2 properties from the `style` attribute (§14.1.2.19).
#[derive(Clone, Debug, Default)]
pub struct VmlStyle {
    /// CSS `position`.
    pub position: Option<CssPosition>,
    /// CSS `left`.
    pub left: Option<VmlLength>,
    /// CSS `top`.
    pub top: Option<VmlLength>,
    /// CSS `width`.
    pub width: Option<VmlLength>,
    /// CSS `height`.
    pub height: Option<VmlLength>,
    /// CSS `margin-left`.
    pub margin_left: Option<VmlLength>,
    /// CSS `margin-top`.
    pub margin_top: Option<VmlLength>,
    /// CSS `margin-right`.
    pub margin_right: Option<VmlLength>,
    /// CSS `margin-bottom`.
    pub margin_bottom: Option<VmlLength>,
    /// CSS `z-index`.
    pub z_index: Option<i64>,
    /// CSS `rotation` (degrees).
    pub rotation: Option<f64>,
    /// VML `flip`.
    pub flip: Option<VmlFlip>,
    /// CSS `visibility`.
    pub visibility: Option<CssVisibility>,
    /// Office `mso-position-horizontal`.
    pub mso_position_horizontal: Option<MsoPositionH>,
    /// Office `mso-position-horizontal-relative`.
    pub mso_position_horizontal_relative: Option<MsoPositionHRelative>,
    /// Office `mso-position-vertical`.
    pub mso_position_vertical: Option<MsoPositionV>,
    /// Office `mso-position-vertical-relative`.
    pub mso_position_vertical_relative: Option<MsoPositionVRelative>,
    /// Office `mso-wrap-distance-left`.
    pub mso_wrap_distance_left: Option<VmlLength>,
    /// Office `mso-wrap-distance-right`.
    pub mso_wrap_distance_right: Option<VmlLength>,
    /// Office `mso-wrap-distance-top`.
    pub mso_wrap_distance_top: Option<VmlLength>,
    /// Office `mso-wrap-distance-bottom`.
    pub mso_wrap_distance_bottom: Option<VmlLength>,
    /// Office `mso-wrap-style`.
    pub mso_wrap_style: Option<MsoWrapStyle>,
}

// ── VML Color ────────────────────────────────────────────────────────────────

/// VML color value (§14.1.2.1 ST_ColorType).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum VmlColor {
    /// Hex-specified sRGB color (r, g, b).
    Rgb(u8, u8, u8),
    /// Predefined named color.
    Named(VmlNamedColor),
}

/// VML/CSS named colors (§14.1.2.1, CSS2.1 §4.3.6, and SVG/CSS3 extended colors).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VmlNamedColor {
    // CSS2.1 §4.3.6 — the 17 standard colors.
    Black,
    Silver,
    Gray,
    White,
    Maroon,
    Red,
    Purple,
    Fuchsia,
    Green,
    Lime,
    Olive,
    Yellow,
    Navy,
    Blue,
    Teal,
    Aqua,
    Orange,
    // SVG/CSS3 extended named colors used in Office documents.
    AliceBlue,
    AntiqueWhite,
    Beige,
    Bisque,
    BlanchedAlmond,
    BlueViolet,
    Brown,
    BurlyWood,
    CadetBlue,
    Chartreuse,
    Chocolate,
    Coral,
    CornflowerBlue,
    Cornsilk,
    Crimson,
    Cyan,
    DarkBlue,
    DarkCyan,
    DarkGoldenrod,
    DarkGray,
    DarkGreen,
    DarkKhaki,
    DarkMagenta,
    DarkOliveGreen,
    DarkOrange,
    DarkOrchid,
    DarkRed,
    DarkSalmon,
    DarkSeaGreen,
    DarkSlateBlue,
    DarkSlateGray,
    DarkTurquoise,
    DarkViolet,
    DeepPink,
    DeepSkyBlue,
    DimGray,
    DodgerBlue,
    Firebrick,
    FloralWhite,
    ForestGreen,
    Gainsboro,
    GhostWhite,
    Gold,
    Goldenrod,
    GreenYellow,
    Honeydew,
    HotPink,
    IndianRed,
    Indigo,
    Ivory,
    Khaki,
    Lavender,
    LavenderBlush,
    LawnGreen,
    LemonChiffon,
    LightBlue,
    LightCoral,
    LightCyan,
    LightGoldenrodYellow,
    LightGray,
    LightGreen,
    LightPink,
    LightSalmon,
    LightSeaGreen,
    LightSkyBlue,
    LightSlateGray,
    LightSteelBlue,
    LightYellow,
    LimeGreen,
    Linen,
    Magenta,
    MediumAquamarine,
    MediumBlue,
    MediumOrchid,
    MediumPurple,
    MediumSeaGreen,
    MediumSlateBlue,
    MediumSpringGreen,
    MediumTurquoise,
    MediumVioletRed,
    MidnightBlue,
    MintCream,
    MistyRose,
    Moccasin,
    NavajoWhite,
    OldLace,
    OliveDrab,
    OrangeRed,
    Orchid,
    PaleGoldenrod,
    PaleGreen,
    PaleTurquoise,
    PaleVioletRed,
    PapayaWhip,
    PeachPuff,
    Peru,
    Pink,
    Plum,
    PowderBlue,
    RosyBrown,
    RoyalBlue,
    SaddleBrown,
    Salmon,
    SandyBrown,
    SeaGreen,
    Seashell,
    Sienna,
    SkyBlue,
    SlateBlue,
    SlateGray,
    Snow,
    SpringGreen,
    SteelBlue,
    Tan,
    Thistle,
    Tomato,
    Turquoise,
    Violet,
    Wheat,
    WhiteSmoke,
    YellowGreen,
    // VML §14.1.2.1 system colors.
    ButtonFace,
    ButtonHighlight,
    ButtonShadow,
    ButtonText,
    CaptionText,
    GrayText,
    Highlight,
    HighlightText,
    InactiveBorder,
    InactiveCaption,
    InactiveCaptionText,
    InfoBackground,
    InfoText,
    Menu,
    MenuText,
    Scrollbar,
    ThreeDDarkShadow,
    ThreeDFace,
    ThreeDHighlight,
    ThreeDLightShadow,
    ThreeDShadow,
    Window,
    WindowFrame,
    WindowText,
}

// ── CSS Enums ────────────────────────────────────────────────────────────────

/// CSS2 `position` property values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CssPosition {
    Static,
    Relative,
    Absolute,
}

/// CSS2 `visibility` property values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CssVisibility {
    Visible,
    Hidden,
    Inherit,
}

/// VML `flip` attribute values (§14.1.2.19).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlFlip {
    /// Flip along the x-axis.
    X,
    /// Flip along the y-axis.
    Y,
    /// Flip along both axes.
    XY,
}

// ── MSO Position / Wrap ──────────────────────────────────────────────────────

/// Office `mso-position-horizontal` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MsoPositionH {
    Absolute,
    Left,
    Center,
    Right,
    Inside,
    Outside,
}

/// Office `mso-position-horizontal-relative` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MsoPositionHRelative {
    Margin,
    Page,
    Text,
    Char,
    LeftMarginArea,
    RightMarginArea,
    InnerMarginArea,
    OuterMarginArea,
}

/// Office `mso-position-vertical` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MsoPositionV {
    Absolute,
    Top,
    Center,
    Bottom,
    Inside,
    Outside,
}

/// Office `mso-position-vertical-relative` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MsoPositionVRelative {
    Margin,
    Page,
    Text,
    Line,
    TopMarginArea,
    BottomMarginArea,
    InnerMarginArea,
    OuterMarginArea,
}

/// Office `mso-wrap-style` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MsoWrapStyle {
    Square,
    None,
    Tight,
    Through,
}

// ── VML Length ────────────────────────────────────────────────────────────────

/// A CSS length value with unit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VmlLength {
    pub value: f64,
    pub unit: VmlLengthUnit,
}

impl VmlLength {
    /// Convert to points when the unit is *absolute*.
    ///
    /// Returns `None` for units this type cannot resolve on its own:
    ///
    /// * [`VmlLengthUnit::Percent`] and [`VmlLengthUnit::Em`] are relative to a
    ///   containing box or font size that only the caller knows.
    /// * [`VmlLengthUnit::None`] — a bare number — means different things in
    ///   different attributes: EMU in a `style` measurement, but *local
    ///   coordinate units* (relative to `coordsize`) on a primitive's
    ///   `from`/`to`/`points`. Callers apply the rule for their own context.
    ///
    /// This carries only the arithmetic that is context-free, so every caller
    /// shares one unit table instead of restating it.
    pub fn to_absolute_points(&self) -> Option<f32> {
        let v = self.value as f32;
        Some(match self.unit {
            VmlLengthUnit::Pt => v,
            VmlLengthUnit::In => v * 72.0,
            VmlLengthUnit::Cm => v * 72.0 / 2.54,
            VmlLengthUnit::Mm => v * 72.0 / 25.4,
            // CSS reference pixel: 96dpi → 72pt/in.
            VmlLengthUnit::Px => v * 0.75,
            VmlLengthUnit::Em | VmlLengthUnit::Percent | VmlLengthUnit::None => return None,
        })
    }
}

/// CSS length unit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlLengthUnit {
    /// Points (pt).
    Pt,
    /// Inches (in).
    In,
    /// Centimeters (cm).
    Cm,
    /// Millimeters (mm).
    Mm,
    /// Pixels (px).
    Px,
    /// Em units (em).
    Em,
    /// Percentage (%).
    Percent,
    /// No unit (bare number, treated as EMU in VML context).
    None,
}

// ── Stroke ───────────────────────────────────────────────────────────────────

/// VML §14.1.2.21: stroke styling.
#[derive(Clone, Debug)]
pub struct VmlStroke {
    /// Dash pattern.
    pub dash_style: Option<VmlDashStyle>,
    /// Line join style.
    pub join_style: Option<VmlJoinStyle>,
}

/// VML §14.1.2.21: stroke dash patterns.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlDashStyle {
    Solid,
    ShortDash,
    ShortDot,
    ShortDashDot,
    ShortDashDotDot,
    Dot,
    Dash,
    LongDash,
    DashDot,
    LongDashDot,
    LongDashDotDot,
}

/// VML §14.1.2.21: line join styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlJoinStyle {
    Round,
    Bevel,
    Miter,
}

// ── Path Properties ──────────────────────────────────────────────────────────

/// VML §14.1.2.14: path properties.
#[derive(Clone, Debug)]
pub struct VmlPath {
    /// o:gradientshapeok — whether the path supports gradient fill.
    pub gradient_shape_ok: Option<bool>,
    /// o:connecttype — connection point type.
    pub connect_type: Option<VmlConnectType>,
    /// o:extrusionok — whether the path supports 3D extrusion.
    pub extrusion_ok: Option<bool>,
}

/// VML o:connecttype — how connection points are defined on the shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VmlConnectType {
    /// No connection points.
    None,
    /// Four connection points at the rectangle midpoints.
    Rect,
    /// Connection points derived from path segments.
    Segments,
    /// Custom connection points.
    Custom,
}

// ── Text Box ─────────────────────────────────────────────────────────────────

/// VML §14.1.2.22: text box inset margins (comma-separated CSS lengths).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VmlTextBoxInset {
    pub left: Option<VmlLength>,
    pub top: Option<VmlLength>,
    pub right: Option<VmlLength>,
    pub bottom: Option<VmlLength>,
}

/// VML §14.1.2.22: text box within a shape.
#[derive(Clone, Debug)]
pub struct VmlTextBox {
    /// Parsed CSS2 style properties.
    pub style: VmlStyle,
    /// VML §14.1.2.22: inset margins (top, left, bottom, right).
    pub inset: Option<VmlTextBoxInset>,
    /// §17.17.1: block-level content from w:txbxContent.
    pub content: Vec<Block>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn common_with_id(id: &str) -> VmlCommonAttrs {
        VmlCommonAttrs {
            id: Some(VmlShapeId::new(id)),
            ..Default::default()
        }
    }

    fn shape(id: &str) -> VmlPrimitive {
        VmlPrimitive::Shape(VmlShape {
            common: common_with_id(id),
            shape_type_ref: None,
            vml_path: None,
        })
    }

    #[test]
    fn pict_shapes_filters_to_shape_variant() {
        // Only the `<v:shape>` primitives are yielded; rect/oval are skipped.
        let pict = Pict {
            shape_type: None,
            primitives: vec![
                shape("s1"),
                VmlPrimitive::Rect(VmlRect {
                    common: common_with_id("r1"),
                }),
                shape("s2"),
                VmlPrimitive::Oval(VmlOval {
                    common: common_with_id("o1"),
                }),
            ],
        };
        let ids: Vec<&str> = pict
            .shapes()
            .map(|s| s.common.id.as_ref().unwrap().as_str())
            .collect();
        assert_eq!(ids, ["s1", "s2"]);
    }

    #[test]
    fn pict_shapes_mut_allows_mutation() {
        let mut pict = Pict {
            shape_type: None,
            primitives: vec![shape("s1")],
        };
        for s in pict.shapes_mut() {
            s.common.id = Some(VmlShapeId::new("changed"));
        }
        assert_eq!(
            pict.shapes()
                .next()
                .unwrap()
                .common
                .id
                .as_ref()
                .unwrap()
                .as_str(),
            "changed"
        );
    }

    /// Every `VmlPrimitive` variant must return its own `common` — guards the
    /// large match in `common()` against a mis-wired arm.
    #[test]
    fn common_returns_each_variants_attrs() {
        let variants = [
            shape("a"),
            VmlPrimitive::Rect(VmlRect {
                common: common_with_id("b"),
            }),
            VmlPrimitive::RoundRect(VmlRoundRect {
                common: common_with_id("c"),
                arcsize: None,
            }),
            VmlPrimitive::Oval(VmlOval {
                common: common_with_id("d"),
            }),
            VmlPrimitive::Line(VmlLine {
                common: common_with_id("e"),
                from: None,
                to: None,
            }),
            VmlPrimitive::PolyLine(VmlPolyLine {
                common: common_with_id("f"),
                points: vec![],
            }),
            VmlPrimitive::Arc(VmlArc {
                common: common_with_id("g"),
                start_angle: None,
                end_angle: None,
            }),
            VmlPrimitive::Curve(VmlCurve {
                common: common_with_id("h"),
                from: None,
                control1: None,
                control2: None,
                to: None,
            }),
            VmlPrimitive::Image(VmlImage {
                common: common_with_id("i"),
                src: None,
            }),
            VmlPrimitive::Group(Box::new(VmlGroup {
                common: common_with_id("j"),
                coord_size: None,
                coord_origin: None,
                children: vec![],
            })),
        ];
        let ids: Vec<&str> = variants
            .iter()
            .map(|p| p.common().id.as_ref().unwrap().as_str())
            .collect();
        assert_eq!(ids, ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]);
    }

    #[test]
    fn common_mut_mutates_in_place() {
        let mut p = VmlPrimitive::Rect(VmlRect {
            common: common_with_id("before"),
        });
        p.common_mut().id = Some(VmlShapeId::new("after"));
        assert_eq!(p.common().id.as_ref().unwrap().as_str(), "after");
    }

    // ── §14.1.2 length units ─────────────────────────────────────────────

    fn len(value: f64, unit: VmlLengthUnit) -> VmlLength {
        VmlLength { value, unit }
    }

    #[test]
    fn absolute_units_convert_to_points() {
        let cases = [
            (len(9.0, VmlLengthUnit::Pt), 9.0),
            (len(1.0, VmlLengthUnit::In), 72.0),
            (len(2.54, VmlLengthUnit::Cm), 72.0),
            (len(25.4, VmlLengthUnit::Mm), 72.0),
            (len(96.0, VmlLengthUnit::Px), 72.0), // 96dpi reference pixel
        ];
        for (input, expected) in cases {
            let got = input.to_absolute_points().expect("absolute unit resolves");
            assert!(
                (got - expected).abs() < 1e-3,
                "{:?} → {got}, expected {expected}",
                input.unit
            );
        }
    }

    /// Units that need a containing box, a font size, or the attribute's own
    /// context are `None` — never a fabricated number. Three separate
    /// converters previously each invented their own answer here, and they
    /// disagreed: a bare number was EMU in one and points in the others.
    #[test]
    fn context_dependent_units_are_unresolved() {
        for unit in [
            VmlLengthUnit::Percent,
            VmlLengthUnit::Em,
            VmlLengthUnit::None,
        ] {
            assert_eq!(
                len(50.0, unit).to_absolute_points(),
                None,
                "{unit:?} cannot be resolved without context"
            );
        }
    }
}