drawingml 1.0.0

Shared DrawingML content model (shapes, fills, colors, lines) for the WordprocessingML/SpreadsheetML/PresentationML crates.
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
//! Writing this crate's model out to DrawingML XML fragments.
//!
//! Every function here writes a **fragment**, never a whole XML document and never the
//! `<a:spPr>`/`<xdr:spPr>`/`<p:spPr>`/`<wps:spPr>` wrapper element itself — that wrapper's name
//! (and namespace prefix) is host-specific, so opening/closing it is each host crate's own
//! responsibility (not yet wired into any of them — see the crate-level doc comment in `lib.rs`).
//! Callers are expected to have already declared the
//! `xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"` namespace on an ancestor
//! element; nothing here writes that declaration.

use std::io::Write;

use xml_core::{BytesEnd, BytesStart, BytesText, Event, Writer};

use crate::error::Result;
use crate::model::{
    BlipFill, BlipFillMode, BulletColor, BulletFont, BulletKind, BulletSize, Color, CropRect,
    CustomGeometry, EffectList, Fill, Geometry, GeometryAdjustment, GradientFill, GradientStop,
    Line, LineEnd, LineJoin, PathCommand, PatternFill, ShapeProperties, TextAutofit, TextBody,
    TextBodyProperties, TextParagraph, TextParagraphProperties, TextRun, TextRunProperties,
    TextSpacing, Transform2D,
};

/// Validates a [`TextRun::Field`]'s `id` against `ST_Guid`
/// (`\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}`, confirmed against the
/// ECMA-376/ISO-IEC 29500-4 `dml-main.xsd` schema — `CT_TextField@id` is typed `s:ST_Guid`,
/// required). Same bug class, and same fix shape, as `powerpoint-ooxml`'s table-style-id
/// validation: a caller-supplied non-GUID id must fail loudly here rather than silently producing
/// schema-invalid `<a:fld>` XML.
fn validate_field_id(id: &str) -> Result<()> {
    let bytes = id.as_bytes();
    let is_hex_run = |s: &[u8], len: usize| s.len() == len && s.iter().all(u8::is_ascii_hexdigit);
    let valid = bytes.len() == 38
        && bytes[0] == b'{'
        && bytes[37] == b'}'
        && bytes[9] == b'-'
        && bytes[14] == b'-'
        && bytes[19] == b'-'
        && bytes[24] == b'-'
        && is_hex_run(&bytes[1..9], 8)
        && is_hex_run(&bytes[10..14], 4)
        && is_hex_run(&bytes[15..19], 4)
        && is_hex_run(&bytes[20..24], 4)
        && is_hex_run(&bytes[25..37], 12)
        // ST_Guid's pattern is `[0-9A-F]`, not `[0-9A-Fa-f]` — reject lowercase too rather than
        // silently accepting XML a strict validator would still flag.
        && id.chars().all(|c| !c.is_ascii_hexdigit() || c.is_ascii_digit() || c.is_ascii_uppercase());
    if valid {
        Ok(())
    } else {
        Err(crate::error::Error::InvalidFieldId(id.to_string()))
    }
}

/// Writes `<a:xfrm>`/`EG_Geometry`/`EG_FillProperties`/`<a:ln>`, in that schema order — the content
/// of `CT_ShapeProperties`, i.e. what a host crate's own `<*:spPr>` wrapper should contain.
pub fn write_shape_properties<W: Write>(
    writer: &mut Writer<W>,
    properties: &ShapeProperties,
) -> Result<()> {
    if let Some(transform) = &properties.transform {
        write_transform(writer, transform)?;
    }
    if let Some(geometry) = &properties.geometry {
        write_geometry(writer, geometry, &properties.geometry_adjustments)?;
    }
    if let Some(fill) = &properties.fill {
        write_fill(writer, fill)?;
    }
    if let Some(line) = &properties.line {
        write_line(writer, line)?;
    }
    if let Some(effects) = &properties.effects {
        write_effect_list(writer, effects)?;
    }
    Ok(())
}

/// Writes `EG_Geometry`/`EG_FillProperties`/`<a:ln>`/`<a:effectLst>`, in that schema order — like
/// [`write_shape_properties`], minus `<a:xfrm>`, and with one difference that matters in practice:
/// when `properties.geometry` is unset, this writes a fixed `<a:prstGeom
/// prst="{default_preset}"><a:avLst/></a:prstGeom>` fallback instead of omitting the geometry
/// element entirely.
///
/// Shared by `word-ooxml`, `excel-ooxml`, and `powerpoint-ooxml`'s own picture/autoshape/connector
/// write sites, since real Office silently refuses to render a shape whose `spPr` has a fill/line
/// but no geometry element at all, so [`write_shape_properties`] alone (which only ever writes a
/// geometry element when the caller explicitly set one) isn't safe to use for a picture or shape
/// that must always render. A single shared implementation also avoids each host crate needing to
/// remember every field independently — in particular `effects`, which is correctly read back into
/// memory by the already-unified [`crate::read_shape_properties`] and must be written back out the
/// same way. Callers write their own `<a:xfrm>` before
/// calling this (deliberately excluded — see this function's own callers for why: Excel's picture
/// position is anchor-driven and always writes a zero-valued placeholder `a:xfrm`; Word derives its
/// `a:xfrm` from the image's own `width_emu`/`height_emu`, never from `properties.transform`;
/// PowerPoint uses `properties.transform` directly).
pub fn write_geometry_fill_line_effects<W: Write>(
    writer: &mut Writer<W>,
    properties: &ShapeProperties,
    default_preset: &str,
) -> Result<()> {
    match &properties.geometry {
        Some(geometry) => write_geometry(writer, geometry, &properties.geometry_adjustments)?,
        None => {
            let mut prst_geom = BytesStart::new("a:prstGeom");
            prst_geom.push_attribute(("prst", default_preset));
            writer.write_event(Event::Start(prst_geom))?;
            writer.write_event(Event::Empty(BytesStart::new("a:avLst")))?;
            writer.write_event(Event::End(BytesEnd::new("a:prstGeom")))?;
        }
    }
    if let Some(fill) = &properties.fill {
        write_fill(writer, fill)?;
    }
    if let Some(line) = &properties.line {
        write_line(writer, line)?;
    }
    if let Some(effects) = &properties.effects {
        write_effect_list(writer, effects)?;
    }
    Ok(())
}

/// Writes `<a:effectLst>`. Self-closing when every effect is unset (schema-valid: `CT_EffectList`'s
/// own effect choices are all `minOccurs="0"`), otherwise wraps whichever of
/// `<a:outerShdw>`/`<a:glow>`/`<a:reflection>`/`<a:softEdge>` are set, in that schema order
/// (`EG_EffectProperties`'s own group definition).
pub fn write_effect_list<W: Write>(writer: &mut Writer<W>, effects: &EffectList) -> Result<()> {
    let has_children = effects.outer_shadow.is_some()
        || effects.glow.is_some()
        || effects.reflection.is_some()
        || effects.soft_edge.is_some();
    if !has_children {
        writer.write_event(Event::Empty(BytesStart::new("a:effectLst")))?;
        return Ok(());
    }

    writer.write_event(Event::Start(BytesStart::new("a:effectLst")))?;
    if let Some(shadow) = &effects.outer_shadow {
        let mut start = BytesStart::new("a:outerShdw");
        if let Some(blur) = shadow.blur_radius_emu {
            start.push_attribute(("blurRad", blur.to_string().as_str()));
        }
        if let Some(distance) = shadow.distance_emu {
            start.push_attribute(("dist", distance.to_string().as_str()));
        }
        if let Some(direction) = shadow.direction_60000ths {
            start.push_attribute(("dir", direction.to_string().as_str()));
        }
        writer.write_event(Event::Start(start))?;
        write_color(writer, &shadow.color)?;
        writer.write_event(Event::End(BytesEnd::new("a:outerShdw")))?;
    }
    if let Some(glow) = &effects.glow {
        let mut start = BytesStart::new("a:glow");
        start.push_attribute(("rad", glow.radius_emu.to_string().as_str()));
        writer.write_event(Event::Start(start))?;
        write_color(writer, &glow.color)?;
        writer.write_event(Event::End(BytesEnd::new("a:glow")))?;
    }
    if let Some(reflection) = &effects.reflection {
        let mut start = BytesStart::new("a:reflection");
        if let Some(blur) = reflection.blur_radius_emu {
            start.push_attribute(("blurRad", blur.to_string().as_str()));
        }
        if let Some(distance) = reflection.distance_emu {
            start.push_attribute(("dist", distance.to_string().as_str()));
        }
        if let Some(direction) = reflection.direction_60000ths {
            start.push_attribute(("dir", direction.to_string().as_str()));
        }
        if let Some(start_alpha) = reflection.start_alpha_1000ths_percent {
            start.push_attribute(("stA", start_alpha.to_string().as_str()));
        }
        if let Some(end_alpha) = reflection.end_alpha_1000ths_percent {
            start.push_attribute(("endA", end_alpha.to_string().as_str()));
        }
        writer.write_event(Event::Empty(start))?;
    }
    if let Some(soft_edge) = &effects.soft_edge {
        let mut start = BytesStart::new("a:softEdge");
        start.push_attribute(("rad", soft_edge.radius_emu.to_string().as_str()));
        writer.write_event(Event::Empty(start))?;
    }
    writer.write_event(Event::End(BytesEnd::new("a:effectLst")))?;
    Ok(())
}

/// Writes `<a:xfrm rot=".." flipH=".." flipV=".."><a:off../><a:ext../></a:xfrm>`.
pub fn write_transform<W: Write>(writer: &mut Writer<W>, transform: &Transform2D) -> Result<()> {
    let mut start = BytesStart::new("a:xfrm");
    if transform.rotation_60000ths != 0 {
        start.push_attribute(("rot", transform.rotation_60000ths.to_string().as_str()));
    }
    if transform.flip_horizontal {
        start.push_attribute(("flipH", "1"));
    }
    if transform.flip_vertical {
        start.push_attribute(("flipV", "1"));
    }

    if transform.offset.is_none() && transform.extent.is_none() {
        writer.write_event(Event::Empty(start))?;
        return Ok(());
    }

    writer.write_event(Event::Start(start))?;
    if let Some((x, y)) = transform.offset {
        let mut off = BytesStart::new("a:off");
        off.push_attribute(("x", x.to_string().as_str()));
        off.push_attribute(("y", y.to_string().as_str()));
        writer.write_event(Event::Empty(off))?;
    }
    if let Some((cx, cy)) = transform.extent {
        let mut ext = BytesStart::new("a:ext");
        ext.push_attribute(("cx", cx.to_string().as_str()));
        ext.push_attribute(("cy", cy.to_string().as_str()));
        writer.write_event(Event::Empty(ext))?;
    }
    writer.write_event(Event::End(BytesEnd::new("a:xfrm")))?;
    Ok(())
}

/// Writes `EG_Geometry` — `<a:prstGeom prst="..">` or `<a:custGeom>..` (see [`Geometry`]'s doc
/// comment for what `custGeom` scope is modeled).
///
/// `adjustments` writes a preset shape's own `<a:avLst>` (adjustment handle values, e.g. a rounded
/// rectangle's corner radius) — ignored for `Geometry::Custom` (which has no `avLst` of its own;
/// see [`ShapeProperties::geometry_adjustments`]'s doc comment for why this is a separate
/// parameter/field rather than living inside [`Geometry::Preset`] itself). Pass `&[]` when there
/// are none to set (the overwhelmingly common case — most preset shapes use their own built-in
/// defaults).
pub fn write_geometry<W: Write>(
    writer: &mut Writer<W>,
    geometry: &Geometry,
    adjustments: &[GeometryAdjustment],
) -> Result<()> {
    match geometry {
        Geometry::Preset(shape) => {
            let mut start = BytesStart::new("a:prstGeom");
            start.push_attribute(("prst", shape.xml_token()));
            if adjustments.is_empty() {
                writer.write_event(Event::Empty(start))?;
            } else {
                writer.write_event(Event::Start(start))?;
                writer.write_event(Event::Start(BytesStart::new("a:avLst")))?;
                for adjustment in adjustments {
                    let mut gd = BytesStart::new("a:gd");
                    gd.push_attribute(("name", adjustment.name.as_str()));
                    gd.push_attribute(("fmla", adjustment.formula.as_str()));
                    writer.write_event(Event::Empty(gd))?;
                }
                writer.write_event(Event::End(BytesEnd::new("a:avLst")))?;
                writer.write_event(Event::End(BytesEnd::new("a:prstGeom")))?;
            }
        }
        Geometry::Custom(custom) => write_custom_geometry(writer, custom)?,
    }
    Ok(())
}

/// Writes `<a:custGeom><a:pathLst><a:path w="." h=".">`'s draw
/// commands`</a:path></a:pathLst></a:custGeom>`. Omits
/// `<a:avLst>`/`<a:gdLst>`/`<a:ahLst>`/`<a:cxnLst>`/`<a:rect>` entirely (all `minOccurs="0"`, none
/// modeled — see [`Geometry::Custom`]'s doc comment).
fn write_custom_geometry<W: Write>(writer: &mut Writer<W>, custom: &CustomGeometry) -> Result<()> {
    writer.write_event(Event::Start(BytesStart::new("a:custGeom")))?;
    writer.write_event(Event::Start(BytesStart::new("a:pathLst")))?;

    let mut path = BytesStart::new("a:path");
    path.push_attribute(("w", custom.width_emu.to_string().as_str()));
    path.push_attribute(("h", custom.height_emu.to_string().as_str()));
    if custom.commands.is_empty() {
        writer.write_event(Event::Empty(path))?;
    } else {
        writer.write_event(Event::Start(path))?;
        for command in &custom.commands {
            write_path_command(writer, command)?;
        }
        writer.write_event(Event::End(BytesEnd::new("a:path")))?;
    }

    writer.write_event(Event::End(BytesEnd::new("a:pathLst")))?;
    writer.write_event(Event::End(BytesEnd::new("a:custGeom")))?;
    Ok(())
}

fn write_path_command<W: Write>(writer: &mut Writer<W>, command: &PathCommand) -> Result<()> {
    match command {
        PathCommand::MoveTo { x, y } => {
            writer.write_event(Event::Start(BytesStart::new("a:moveTo")))?;
            write_path_point(writer, *x, *y)?;
            writer.write_event(Event::End(BytesEnd::new("a:moveTo")))?;
        }
        PathCommand::LineTo { x, y } => {
            writer.write_event(Event::Start(BytesStart::new("a:lnTo")))?;
            write_path_point(writer, *x, *y)?;
            writer.write_event(Event::End(BytesEnd::new("a:lnTo")))?;
        }
        PathCommand::CubicBezierTo {
            x1,
            y1,
            x2,
            y2,
            x,
            y,
        } => {
            writer.write_event(Event::Start(BytesStart::new("a:cubicBezTo")))?;
            write_path_point(writer, *x1, *y1)?;
            write_path_point(writer, *x2, *y2)?;
            write_path_point(writer, *x, *y)?;
            writer.write_event(Event::End(BytesEnd::new("a:cubicBezTo")))?;
        }
        PathCommand::Close => {
            writer.write_event(Event::Empty(BytesStart::new("a:close")))?;
        }
    }
    Ok(())
}

fn write_path_point<W: Write>(writer: &mut Writer<W>, x: i64, y: i64) -> Result<()> {
    let mut pt = BytesStart::new("a:pt");
    pt.push_attribute(("x", x.to_string().as_str()));
    pt.push_attribute(("y", y.to_string().as_str()));
    writer.write_event(Event::Empty(pt))?;
    Ok(())
}

/// Writes `EG_FillProperties` — `<a:noFill/>`, `<a:solidFill>..`, `<a:gradFill>..`,
/// `<a:pattFill>..`, or `<a:blipFill>..`.
pub fn write_fill<W: Write>(writer: &mut Writer<W>, fill: &Fill) -> Result<()> {
    match fill {
        Fill::None => writer.write_event(Event::Empty(BytesStart::new("a:noFill")))?,
        Fill::Solid(color) => {
            writer.write_event(Event::Start(BytesStart::new("a:solidFill")))?;
            write_color(writer, color)?;
            writer.write_event(Event::End(BytesEnd::new("a:solidFill")))?;
        }
        Fill::Gradient(gradient) => write_gradient_fill(writer, gradient)?,
        Fill::Pattern(pattern) => write_pattern_fill(writer, pattern)?,
        Fill::Image(blip_fill) => write_blip_fill(writer, blip_fill)?,
    }
    Ok(())
}

/// Writes `<a:blipFill>` — (`<a:blip>`/stretch-or-tile), (`<a:srcRect>`). See [`BlipFill`]'s doc
/// comment for what else isn't modeled (no per-mode tiling/stretching sub-rects).
pub fn write_blip_fill<W: Write>(writer: &mut Writer<W>, blip_fill: &BlipFill) -> Result<()> {
    let has_children =
        blip_fill.relationship_id.is_some() || blip_fill.crop.is_some() || blip_fill.mode.is_some();
    if !has_children {
        writer.write_event(Event::Empty(BytesStart::new("a:blipFill")))?;
        return Ok(());
    }

    writer.write_event(Event::Start(BytesStart::new("a:blipFill")))?;
    if let Some(relationship_id) = &blip_fill.relationship_id {
        let mut blip = BytesStart::new("a:blip");
        blip.push_attribute(("r:embed", relationship_id.as_str()));
        writer.write_event(Event::Empty(blip))?;
    }
    if let Some(crop) = &blip_fill.crop {
        write_crop_rect(writer, crop)?;
    }
    if let Some(mode) = &blip_fill.mode {
        let element_name = match mode {
            BlipFillMode::Stretch => "a:stretch",
            BlipFillMode::Tile => "a:tile",
        };
        writer.write_event(Event::Empty(BytesStart::new(element_name)))?;
    }
    writer.write_event(Event::End(BytesEnd::new("a:blipFill")))?;
    Ok(())
}

/// Writes `<a:srcRect l="." t="." r="." b="."/>`.
fn write_crop_rect<W: Write>(writer: &mut Writer<W>, crop: &CropRect) -> Result<()> {
    let mut start = BytesStart::new("a:srcRect");
    if let Some(left) = crop.left_1000ths_percent {
        start.push_attribute(("l", left.to_string().as_str()));
    }
    if let Some(top) = crop.top_1000ths_percent {
        start.push_attribute(("t", top.to_string().as_str()));
    }
    if let Some(right) = crop.right_1000ths_percent {
        start.push_attribute(("r", right.to_string().as_str()));
    }
    if let Some(bottom) = crop.bottom_1000ths_percent {
        start.push_attribute(("b", bottom.to_string().as_str()));
    }
    writer.write_event(Event::Empty(start))?;
    Ok(())
}

fn write_gradient_fill<W: Write>(writer: &mut Writer<W>, gradient: &GradientFill) -> Result<()> {
    writer.write_event(Event::Start(BytesStart::new("a:gradFill")))?;

    if !gradient.stops.is_empty() {
        writer.write_event(Event::Start(BytesStart::new("a:gsLst")))?;
        for stop in &gradient.stops {
            write_gradient_stop(writer, stop)?;
        }
        writer.write_event(Event::End(BytesEnd::new("a:gsLst")))?;
    }

    if let Some(angle) = gradient.angle_60000ths {
        let mut lin = BytesStart::new("a:lin");
        lin.push_attribute(("ang", angle.to_string().as_str()));
        writer.write_event(Event::Empty(lin))?;
    }

    writer.write_event(Event::End(BytesEnd::new("a:gradFill")))?;
    Ok(())
}

fn write_gradient_stop<W: Write>(writer: &mut Writer<W>, stop: &GradientStop) -> Result<()> {
    let mut start = BytesStart::new("a:gs");
    start.push_attribute(("pos", stop.position_1000ths_percent.to_string().as_str()));
    writer.write_event(Event::Start(start))?;
    write_color(writer, &stop.color)?;
    writer.write_event(Event::End(BytesEnd::new("a:gs")))?;
    Ok(())
}

fn write_pattern_fill<W: Write>(writer: &mut Writer<W>, pattern: &PatternFill) -> Result<()> {
    let mut start = BytesStart::new("a:pattFill");
    start.push_attribute(("prst", pattern.preset.xml_token()));

    if pattern.foreground.is_none() && pattern.background.is_none() {
        writer.write_event(Event::Empty(start))?;
        return Ok(());
    }

    writer.write_event(Event::Start(start))?;
    if let Some(color) = &pattern.foreground {
        writer.write_event(Event::Start(BytesStart::new("a:fgClr")))?;
        write_color(writer, color)?;
        writer.write_event(Event::End(BytesEnd::new("a:fgClr")))?;
    }
    if let Some(color) = &pattern.background {
        writer.write_event(Event::Start(BytesStart::new("a:bgClr")))?;
        write_color(writer, color)?;
        writer.write_event(Event::End(BytesEnd::new("a:bgClr")))?;
    }
    writer.write_event(Event::End(BytesEnd::new("a:pattFill")))?;
    Ok(())
}

/// Writes `EG_ColorChoice` — a single `<a:srgbClr../>`, `<a:scrgbClr../>`, `<a:hslClr../>`,
/// `<a:sysClr../>`, or `<a:prstClr../>` element, with no wrapping element of its own (the caller —
/// `<a:solidFill>`, `<a:fgClr>`, `<a:gs>`. — provides that).
pub fn write_color<W: Write>(writer: &mut Writer<W>, color: &Color) -> Result<()> {
    match color {
        Color::Rgb(hex) => {
            let mut start = BytesStart::new("a:srgbClr");
            start.push_attribute(("val", hex.as_str()));
            writer.write_event(Event::Empty(start))?;
        }
        Color::RgbPercent { red, green, blue } => {
            let mut start = BytesStart::new("a:scrgbClr");
            start.push_attribute(("r", red.to_string().as_str()));
            start.push_attribute(("g", green.to_string().as_str()));
            start.push_attribute(("b", blue.to_string().as_str()));
            writer.write_event(Event::Empty(start))?;
        }
        Color::Hsl {
            hue_60000ths,
            saturation_1000ths_percent,
            luminance_1000ths_percent,
        } => {
            let mut start = BytesStart::new("a:hslClr");
            start.push_attribute(("hue", hue_60000ths.to_string().as_str()));
            start.push_attribute(("sat", saturation_1000ths_percent.to_string().as_str()));
            start.push_attribute(("lum", luminance_1000ths_percent.to_string().as_str()));
            writer.write_event(Event::Empty(start))?;
        }
        Color::System { value, last_color } => {
            let mut start = BytesStart::new("a:sysClr");
            start.push_attribute(("val", value.as_str()));
            if let Some(last_color) = last_color {
                start.push_attribute(("lastClr", last_color.as_str()));
            }
            writer.write_event(Event::Empty(start))?;
        }
        Color::Preset(name) => {
            let mut start = BytesStart::new("a:prstClr");
            start.push_attribute(("val", name.as_str()));
            writer.write_event(Event::Empty(start))?;
        }
    }
    Ok(())
}

/// Writes `<a:ln w="..">EG_LineFillProperties, EG_LineDashProperties, EG_LineJoinProperties,
/// headEnd?, tailEnd?</a:ln>`.
pub fn write_line<W: Write>(writer: &mut Writer<W>, line: &Line) -> Result<()> {
    write_line_named(writer, "a:ln", line)
}

/// Writes a `CT_LineProperties`-typed element under a caller-chosen name — same content model as
/// [`write_line`] (which is just this called with `"a:ln"`), for the handful of other elements in
/// the wider OOXML vocabulary that reuse `CT_LineProperties` under a different name, e.g.
/// PresentationML table cell borders (`<a:lnL>`/`<a:lnR>`/`<a:lnT>`/ `<a:lnB>`,
/// `powerpoint-ooxml`'s own [`crate`]-external `TableCellProperties`, point 8).
pub fn write_line_named<W: Write>(
    writer: &mut Writer<W>,
    element_name: &str,
    line: &Line,
) -> Result<()> {
    let mut start = BytesStart::new(element_name);
    if let Some(width) = line.width_emu {
        start.push_attribute(("w", width.to_string().as_str()));
    }
    if let Some(cap) = &line.cap {
        start.push_attribute(("cap", cap.xml_token()));
    }
    if let Some(compound) = &line.compound {
        start.push_attribute(("cmpd", compound.xml_token()));
    }

    let has_children = line.fill.is_some()
        || line.dash.is_some()
        || line.join.is_some()
        || line.head_end.is_some()
        || line.tail_end.is_some();
    if !has_children {
        writer.write_event(Event::Empty(start))?;
        return Ok(());
    }

    writer.write_event(Event::Start(start))?;
    if let Some(fill) = &line.fill {
        write_fill(writer, fill)?;
    }
    if let Some(dash) = &line.dash {
        let mut prst_dash = BytesStart::new("a:prstDash");
        prst_dash.push_attribute(("val", dash.xml_token()));
        writer.write_event(Event::Empty(prst_dash))?;
    }
    if let Some(join) = &line.join {
        write_line_join(writer, join)?;
    }
    if let Some(head_end) = &line.head_end {
        write_line_end(writer, "a:headEnd", head_end)?;
    }
    if let Some(tail_end) = &line.tail_end {
        write_line_end(writer, "a:tailEnd", tail_end)?;
    }
    writer.write_event(Event::End(BytesEnd::new(element_name)))?;
    Ok(())
}

fn write_line_join<W: Write>(writer: &mut Writer<W>, join: &LineJoin) -> Result<()> {
    match join {
        LineJoin::Round => writer.write_event(Event::Empty(BytesStart::new("a:round")))?,
        LineJoin::Bevel => writer.write_event(Event::Empty(BytesStart::new("a:bevel")))?,
        LineJoin::Miter {
            limit_1000ths_percent,
        } => {
            let mut start = BytesStart::new("a:miter");
            if let Some(limit) = limit_1000ths_percent {
                start.push_attribute(("lim", limit.to_string().as_str()));
            }
            writer.write_event(Event::Empty(start))?;
        }
    }
    Ok(())
}

fn write_line_end<W: Write>(
    writer: &mut Writer<W>,
    element_name: &str,
    end: &LineEnd,
) -> Result<()> {
    let mut start = BytesStart::new(element_name);
    if let Some(kind) = &end.kind {
        start.push_attribute(("type", kind.xml_token()));
    }
    if let Some(width) = &end.width {
        start.push_attribute(("w", width.xml_token()));
    }
    if let Some(length) = &end.length {
        start.push_attribute(("len", length.xml_token()));
    }
    writer.write_event(Event::Empty(start))?;
    Ok(())
}

// ================================================================================================
// Text-in-shape (`<a:txBody>`)
// ================================================================================================

/// Writes `<a:bodyPr>../<a:p>..</a:p>*` — the content of `<a:txBody>` (`CT_TextBody`). Like
/// [`write_shape_properties`], never writes the `<a:txBody>` wrapper itself (a sibling of
/// `<a:spPr>` inside a host's own `<*:sp>`, not this crate's concern — see [`crate::TextBody`]'s
/// doc comment).
pub fn write_text_body<W: Write>(writer: &mut Writer<W>, body: &TextBody) -> Result<()> {
    write_text_body_properties(writer, &body.properties)?;
    for paragraph in &body.paragraphs {
        write_text_paragraph(writer, paragraph)?;
    }
    Ok(())
}

/// Writes `<a:bodyPr>` (self-closing unless `autofit` is set — no 3D/preset warp modeled, see
/// [`TextBody`]'s doc comment), matching the schema's own `minOccurs="1"` on this element even when
/// everything is unset (`<a:bodyPr/>`).
pub fn write_text_body_properties<W: Write>(
    writer: &mut Writer<W>,
    properties: &TextBodyProperties,
) -> Result<()> {
    let mut start = BytesStart::new("a:bodyPr");
    if properties.rotation_60000ths != 0 {
        start.push_attribute(("rot", properties.rotation_60000ths.to_string().as_str()));
    }
    if let Some(vertical_direction) = &properties.vertical_direction {
        start.push_attribute(("vert", vertical_direction.xml_token()));
    }
    if let Some(wrap) = &properties.wrap {
        start.push_attribute(("wrap", wrap.xml_token()));
    }
    if let Some(anchor) = &properties.anchor {
        start.push_attribute(("anchor", anchor.xml_token()));
    }
    if properties.anchor_center {
        start.push_attribute(("anchorCtr", "1"));
    }
    if let Some(inset) = properties.inset_left_emu {
        start.push_attribute(("lIns", inset.to_string().as_str()));
    }
    if let Some(inset) = properties.inset_top_emu {
        start.push_attribute(("tIns", inset.to_string().as_str()));
    }
    if let Some(inset) = properties.inset_right_emu {
        start.push_attribute(("rIns", inset.to_string().as_str()));
    }
    if let Some(inset) = properties.inset_bottom_emu {
        start.push_attribute(("bIns", inset.to_string().as_str()));
    }

    let Some(autofit) = &properties.autofit else {
        writer.write_event(Event::Empty(start))?;
        return Ok(());
    };

    writer.write_event(Event::Start(start))?;
    match autofit {
        TextAutofit::None => writer.write_event(Event::Empty(BytesStart::new("a:noAutofit")))?,
        TextAutofit::Shape => writer.write_event(Event::Empty(BytesStart::new("a:spAutoFit")))?,
        TextAutofit::Normal {
            font_scale_1000ths_percent,
            line_spacing_reduction_1000ths_percent,
        } => {
            let mut element = BytesStart::new("a:normAutofit");
            if let Some(scale) = font_scale_1000ths_percent {
                element.push_attribute(("fontScale", scale.to_string().as_str()));
            }
            if let Some(reduction) = line_spacing_reduction_1000ths_percent {
                element.push_attribute(("lnSpcReduction", reduction.to_string().as_str()));
            }
            writer.write_event(Event::Empty(element))?;
        }
    }
    writer.write_event(Event::End(BytesEnd::new("a:bodyPr")))?;
    Ok(())
}

/// Writes `<a:p><a:pPr../>EG_TextRun*</a:p>` (`CT_TextParagraph`).
pub fn write_text_paragraph<W: Write>(
    writer: &mut Writer<W>,
    paragraph: &TextParagraph,
) -> Result<()> {
    writer.write_event(Event::Start(BytesStart::new("a:p")))?;
    if let Some(properties) = &paragraph.properties {
        write_text_paragraph_properties(writer, properties)?;
    }
    for run in &paragraph.runs {
        write_text_run(writer, run)?;
    }
    writer.write_event(Event::End(BytesEnd::new("a:p")))?;
    Ok(())
}

/// Writes `<a:pPr>` — self-closing when nothing beyond its own attributes is set, otherwise wraps
/// `<a:lnSpc>`/`<a:spcBef>`/`<a:spcAft>`/bullet elements/`<a:tabLst>`/`<a:defRPr>` children, in
/// that order — the same child sequence confirmed on a real fixture
/// (`<a:lnSpc>..<a:spcBef>..<a:spcAft>..<a:buClrTx/><a:buSzTx/>
/// <a:buFontTx/><a:buNone/><a:tabLst/><a:defRPr/>`).
pub fn write_text_paragraph_properties<W: Write>(
    writer: &mut Writer<W>,
    properties: &TextParagraphProperties,
) -> Result<()> {
    let mut start = BytesStart::new("a:pPr");
    if let Some(margin) = properties.margin_left_emu {
        start.push_attribute(("marL", margin.to_string().as_str()));
    }
    if let Some(margin) = properties.margin_right_emu {
        start.push_attribute(("marR", margin.to_string().as_str()));
    }
    if let Some(level) = properties.level {
        start.push_attribute(("lvl", level.to_string().as_str()));
    }
    if let Some(indent) = properties.indent_emu {
        start.push_attribute(("indent", indent.to_string().as_str()));
    }
    if let Some(alignment) = &properties.alignment {
        start.push_attribute(("algn", alignment.xml_token()));
    }

    let has_children = properties.line_spacing.is_some()
        || properties.space_before.is_some()
        || properties.space_after.is_some()
        || properties.bullet_color.is_some()
        || properties.bullet_size.is_some()
        || properties.bullet_font.is_some()
        || properties.bullet.is_some()
        || !properties.tab_stops.is_empty()
        || properties.default_run_properties.is_some();
    if !has_children {
        writer.write_event(Event::Empty(start))?;
        return Ok(());
    }

    writer.write_event(Event::Start(start))?;
    if let Some(spacing) = &properties.line_spacing {
        write_text_spacing(writer, "a:lnSpc", spacing)?;
    }
    if let Some(spacing) = &properties.space_before {
        write_text_spacing(writer, "a:spcBef", spacing)?;
    }
    if let Some(spacing) = &properties.space_after {
        write_text_spacing(writer, "a:spcAft", spacing)?;
    }
    if let Some(color) = &properties.bullet_color {
        match color {
            BulletColor::FollowText => {
                writer.write_event(Event::Empty(BytesStart::new("a:buClrTx")))?
            }
            BulletColor::Explicit(color) => {
                writer.write_event(Event::Start(BytesStart::new("a:buClr")))?;
                write_color(writer, color)?;
                writer.write_event(Event::End(BytesEnd::new("a:buClr")))?;
            }
        }
    }
    if let Some(size) = &properties.bullet_size {
        match size {
            BulletSize::FollowText => {
                writer.write_event(Event::Empty(BytesStart::new("a:buSzTx")))?
            }
            BulletSize::Percent(value) => {
                let mut element = BytesStart::new("a:buSzPct");
                element.push_attribute(("val", value.to_string().as_str()));
                writer.write_event(Event::Empty(element))?;
            }
            BulletSize::Points(value) => {
                let mut element = BytesStart::new("a:buSzPts");
                element.push_attribute(("val", value.to_string().as_str()));
                writer.write_event(Event::Empty(element))?;
            }
        }
    }
    if let Some(font) = &properties.bullet_font {
        match font {
            BulletFont::FollowText => {
                writer.write_event(Event::Empty(BytesStart::new("a:buFontTx")))?
            }
            BulletFont::Typeface(typeface) => {
                let mut element = BytesStart::new("a:buFont");
                element.push_attribute(("typeface", typeface.as_str()));
                writer.write_event(Event::Empty(element))?;
            }
        }
    }
    if let Some(bullet) = &properties.bullet {
        match bullet {
            BulletKind::None => writer.write_event(Event::Empty(BytesStart::new("a:buNone")))?,
            BulletKind::Character(character) => {
                let mut element = BytesStart::new("a:buChar");
                element.push_attribute(("char", character.as_str()));
                writer.write_event(Event::Empty(element))?;
            }
            BulletKind::AutoNumber { scheme, start_at } => {
                let mut element = BytesStart::new("a:buAutoNum");
                element.push_attribute(("type", scheme.as_str()));
                if let Some(start_at) = start_at {
                    element.push_attribute(("startAt", start_at.to_string().as_str()));
                }
                writer.write_event(Event::Empty(element))?;
            }
        }
    }
    if !properties.tab_stops.is_empty() {
        writer.write_event(Event::Start(BytesStart::new("a:tabLst")))?;
        for tab_stop in &properties.tab_stops {
            let mut tab = BytesStart::new("a:tab");
            tab.push_attribute(("pos", tab_stop.position_emu.to_string().as_str()));
            if let Some(alignment) = &tab_stop.alignment {
                tab.push_attribute(("algn", alignment.xml_token()));
            }
            writer.write_event(Event::Empty(tab))?;
        }
        writer.write_event(Event::End(BytesEnd::new("a:tabLst")))?;
    }
    if properties.default_run_properties.is_some() {
        write_text_run_properties(
            writer,
            "a:defRPr",
            properties.default_run_properties.as_deref(),
        )?;
    }
    writer.write_event(Event::End(BytesEnd::new("a:pPr")))?;
    Ok(())
}

/// Writes one `CT_TextSpacing` choice — `<a:spcPct val=".">` or `<a:spcPts val=".">` — wrapped in
/// `element_name` (`<a:lnSpc>`/ `<a:spcBef>`/`<a:spcAft>`).
fn write_text_spacing<W: Write>(
    writer: &mut Writer<W>,
    element_name: &str,
    spacing: &TextSpacing,
) -> Result<()> {
    writer.write_event(Event::Start(BytesStart::new(element_name)))?;
    let (child_name, value) = match spacing {
        TextSpacing::Percent(value) => ("a:spcPct", *value),
        TextSpacing::Points(value) => ("a:spcPts", *value),
    };
    let mut child = BytesStart::new(child_name);
    child.push_attribute(("val", value.to_string().as_str()));
    writer.write_event(Event::Empty(child))?;
    writer.write_event(Event::End(BytesEnd::new(element_name)))?;
    Ok(())
}

/// Writes one `EG_TextRun` choice — `<a:r>..</a:r>` for [`TextRun::Regular`],
/// `<a:br../>`/`<a:br>..</a:br>` for [`TextRun::LineBreak`].
pub fn write_text_run<W: Write>(writer: &mut Writer<W>, run: &TextRun) -> Result<()> {
    match run {
        TextRun::Regular { text, properties } => {
            writer.write_event(Event::Start(BytesStart::new("a:r")))?;
            write_text_run_properties(writer, "a:rPr", Some(properties))?;
            writer.write_event(Event::Start(BytesStart::new("a:t")))?;
            writer.write_event(Event::Text(BytesText::new(text)))?;
            writer.write_event(Event::End(BytesEnd::new("a:t")))?;
            writer.write_event(Event::End(BytesEnd::new("a:r")))?;
        }
        TextRun::LineBreak { properties } => {
            if properties.is_none() {
                writer.write_event(Event::Empty(BytesStart::new("a:br")))?;
            } else {
                writer.write_event(Event::Start(BytesStart::new("a:br")))?;
                write_text_run_properties(writer, "a:rPr", properties.as_ref())?;
                writer.write_event(Event::End(BytesEnd::new("a:br")))?;
            }
        }
        TextRun::Field {
            id,
            field_type,
            cached_text,
            properties,
        } => {
            validate_field_id(id)?;
            let mut start = BytesStart::new("a:fld");
            start.push_attribute(("id", id.as_str()));
            if let Some(field_type) = field_type {
                start.push_attribute(("type", field_type.as_str()));
            }
            writer.write_event(Event::Start(start))?;
            write_text_run_properties(writer, "a:rPr", Some(properties))?;
            writer.write_event(Event::Start(BytesStart::new("a:t")))?;
            writer.write_event(Event::Text(BytesText::new(cached_text)))?;
            writer.write_event(Event::End(BytesEnd::new("a:t")))?;
            writer.write_event(Event::End(BytesEnd::new("a:fld")))?;
        }
    }
    Ok(())
}

/// Writes `<a:rPr b=".." i=".." u=".." strike=".." sz="..">EG_FillProperties?<a:latin
/// typeface=".."/>?</a:rPr>`, or nothing at all when `properties` is `None` (a bare line break with
/// no formatting override) — `element_name` is always `"a:rPr"` in this crate today
/// (`<a:defRPr>`/`<a:endParaRPr>` aren't written, see [`TextRunProperties`]'s doc comment), kept as
/// a parameter for that documented reason rather than hard-coded.
fn write_text_run_properties<W: Write>(
    writer: &mut Writer<W>,
    element_name: &str,
    properties: Option<&TextRunProperties>,
) -> Result<()> {
    let Some(properties) = properties else {
        return Ok(());
    };

    let mut start = BytesStart::new(element_name);
    if properties.bold {
        start.push_attribute(("b", "1"));
    }
    if properties.italic {
        start.push_attribute(("i", "1"));
    }
    if let Some(underline) = &properties.underline {
        start.push_attribute(("u", underline.xml_token()));
    }
    if let Some(strike) = &properties.strike {
        start.push_attribute(("strike", strike.xml_token()));
    }
    if let Some(size) = properties.font_size_100ths_point {
        start.push_attribute(("sz", size.to_string().as_str()));
    }
    if let Some(caps) = &properties.text_caps {
        start.push_attribute(("cap", caps.xml_token()));
    }
    if let Some(spacing) = properties.character_spacing_100ths_point {
        start.push_attribute(("spc", spacing.to_string().as_str()));
    }
    if let Some(baseline) = properties.baseline_1000ths_percent {
        start.push_attribute(("baseline", baseline.to_string().as_str()));
    }

    let has_children = properties.fill.is_some()
        || properties.highlight.is_some()
        || properties.font_family.is_some()
        || properties.hyperlink.is_some();
    if !has_children {
        writer.write_event(Event::Empty(start))?;
        return Ok(());
    }

    writer.write_event(Event::Start(start))?;
    if let Some(fill) = &properties.fill {
        write_fill(writer, fill)?;
    }
    if let Some(highlight) = &properties.highlight {
        writer.write_event(Event::Start(BytesStart::new("a:highlight")))?;
        write_color(writer, highlight)?;
        writer.write_event(Event::End(BytesEnd::new("a:highlight")))?;
    }
    if let Some(font_family) = &properties.font_family {
        let mut latin = BytesStart::new("a:latin");
        latin.push_attribute(("typeface", font_family.as_str()));
        writer.write_event(Event::Empty(latin))?;
    }
    if let Some(hyperlink) = &properties.hyperlink {
        write_hyperlink(writer, "a:hlinkClick", hyperlink)?;
    }
    writer.write_event(Event::End(BytesEnd::new(element_name)))?;
    Ok(())
}

/// Writes `<a:hlinkClick r:id="." tooltip="."/>` (`CT_Hyperlink`). See
/// [`crate::model::Hyperlink`]'s own doc comment for why `relationship_id` is already resolved by
/// the time it reaches here.
fn write_hyperlink<W: Write>(
    writer: &mut Writer<W>,
    element_name: &str,
    hyperlink: &crate::model::Hyperlink,
) -> Result<()> {
    let mut start = BytesStart::new(element_name);
    if let Some(relationship_id) = &hyperlink.relationship_id {
        start.push_attribute(("r:id", relationship_id.as_str()));
    }
    if let Some(tooltip) = &hyperlink.tooltip {
        start.push_attribute(("tooltip", tooltip.as_str()));
    }
    writer.write_event(Event::Empty(start))?;
    Ok(())
}