betteroffice-pptx-parse 0.5.1

Bounded PresentationML parsing and part-preserving PPTX package serialization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
use std::collections::BTreeMap;

pub use ooxml_drawingml::ShapeStyle;
use ooxml_drawingml::{
    ColorMap, ColorValue, GeometryPathCommand, ShapeEffects, ShapeFill, ShapeOutline,
    StyleReference, TableStyleList, Theme, ThemeFormatScheme,
};
use serde::{Deserialize, Serialize};

use crate::comments::{Comment, CommentAuthor, CommentFlavor};
use crate::inventory::{NotesSource, SlideSource};
use crate::relationships::Relationship;

pub use ooxml_drawingml::chart::{
    ChartAxes, ChartAxis, ChartDataLabels, ChartLegend, ChartMarker, ChartPlotGroup, ChartPoint,
    ChartPointLabel, ChartSeries, ChartSpace, ChartTextProperties,
};

/// Shape elements counted by source ordinals.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum ShapeElements {
    WithConnectors,
    #[default]
    WithoutConnectors,
}

impl ShapeElements {
    fn is_legacy(&self) -> bool {
        *self == Self::WithoutConnectors
    }

    pub(crate) fn contains(self, local: &str) -> bool {
        matches!(local, "sp" | "pic" | "graphicFrame" | "grpSp")
            || (self == Self::WithConnectors && local == "cxnSp")
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PptxPackage {
    pub presentation: Presentation,
    pub slides: Vec<Slide>,
    pub layouts: Vec<SlideLayout>,
    pub masters: Vec<SlideMaster>,
    pub themes: Vec<ThemePart>,
    /// Absent from packages serialized before charts were parsed.
    #[serde(default)]
    pub charts: Vec<ChartPart>,
    /// The drawing PowerPoint saves beside each SmartArt graphic.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub diagram_drawings: Vec<DiagramDrawing>,
    pub media: Vec<MediaPart>,
    /// Absent from packages serialized before table styles were parsed.
    #[serde(default, skip_serializing_if = "TableStyleList::is_empty")]
    pub table_styles: TableStyleList,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comment_authors: Vec<CommentAuthor>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<Comment>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment_flavor: Option<CommentFlavor>,
    pub relationships: BTreeMap<String, Vec<Relationship>>,
    #[serde(skip)]
    pub(crate) parts: Vec<PackagePart>,
    /// Source bytes for verbatim member passthrough on save.
    #[serde(skip)]
    pub(crate) source_container: ooxml_opc::SourceContainer,
    #[serde(default, skip_serializing_if = "ShapeElements::is_legacy")]
    pub(crate) shape_elements: ShapeElements,
    /// Source inventories of the slide parts, by part path, found while parsing.
    #[serde(skip)]
    pub(crate) sources: BTreeMap<String, SlideSource>,
    /// Notes pages, by the part path of the slide they belong to.
    #[serde(skip)]
    pub(crate) notes_sources: BTreeMap<String, NotesSource>,
}

impl PptxPackage {
    pub fn part_bytes(&self, path: &str) -> Option<&[u8]> {
        self.parts
            .iter()
            .find(|part| part.path == path)
            .map(|part| part.bytes.as_slice())
    }

    /// Authored other-style levels, including explicitly empty levels when source is attached.
    pub fn master_other_style_levels(&self, master: &SlideMaster) -> [bool; 9] {
        let mut levels = std::array::from_fn(|index| {
            master
                .text_styles
                .other
                .get(index)
                .is_some_and(|properties| properties != &ParagraphProperties::default())
        });
        let Some(bytes) = self.part_bytes(&master.part_path) else {
            return levels;
        };
        let limits = crate::xml::ParseLimits::default();
        let mut budget = crate::xml::ParseBudget::new(&limits);
        let Ok(root) = crate::xml::parse_xml(bytes, &master.part_path, &mut budget) else {
            return levels;
        };
        let other = root
            .child("txStyles")
            .and_then(|styles| styles.child("otherStyle"));
        for (index, present) in levels.iter_mut().enumerate() {
            *present |= other
                .and_then(|style| style.child(&format!("lvl{}pPr", index + 1)))
                .is_some();
        }
        levels
    }

    /// False for packages recovered from a collaboration update, which carry
    /// the parsed model but not the raw part bytes.
    pub fn has_parts(&self) -> bool {
        !self.parts.is_empty()
    }

    /// Where a slide part's shapes sit in its XML and what the model leaves out; `None` for
    /// packages not parsed from file bytes.
    pub fn slide_source(&self, part_path: &str) -> Option<&SlideSource> {
        self.sources.get(part_path)
    }

    /// The notes page of the slide at `slide_part_path`, when the package was parsed with one.
    pub fn notes_source(&self, slide_part_path: &str) -> Option<&NotesSource> {
        self.notes_sources.get(slide_part_path)
    }

    /// Whether source ordinals include connectors.
    pub fn models_connectors(&self) -> bool {
        self.shape_elements == ShapeElements::WithConnectors
    }

    pub fn replace_part(&mut self, path: &str, bytes: Vec<u8>) -> bool {
        let Some(part) = self.parts.iter_mut().find(|part| part.path == path) else {
            return false;
        };
        part.bytes = bytes;
        true
    }
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PackagePart {
    pub path: String,
    pub bytes: Vec<u8>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Presentation {
    pub part_path: String,
    pub width_emu: i64,
    pub height_emu: i64,
    /// `p:presentation/@firstSlideNum`.
    #[serde(
        default = "default_first_slide_num",
        skip_serializing_if = "is_default_first_slide_num"
    )]
    pub first_slide_num: i32,
    pub slides: Vec<SlideReference>,
    pub master_part_paths: Vec<String>,
    /// `p:defaultTextStyle`, one entry per list level.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub default_text_style: Vec<ParagraphProperties>,
    /// `p:defaultTextStyle/a:defPPr`, under every level.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_text_paragraph: Option<Box<ParagraphProperties>>,
}

fn default_first_slide_num() -> i32 {
    1
}

fn is_default_first_slide_num(value: &i32) -> bool {
    *value == default_first_slide_num()
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SlideReference {
    pub id: u32,
    pub relationship_id: String,
    pub part_path: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Slide {
    pub part_path: String,
    pub name: Option<String>,
    pub layout_part_path: Option<String>,
    pub show_master_shapes: bool,
    pub background: Option<ShapeFill>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_picture: Option<Box<PictureFill>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_reference: Option<StyleReference>,
    /// `p:cSld` declares `p:bg`, whatever fill it holds; `false` in packages
    /// stored before it was read.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub declares_background: bool,
    pub shapes: Vec<ShapeNode>,
    /// `p:clrMapOvr/a:overrideClrMapping`; absent when the parent map applies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color_map_override: Option<ColorMap>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub notes: String,
    /// `p:sld/@show` negated; `None` in packages stored before slide visibility was read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hidden: Option<bool>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SlideLayout {
    pub part_path: String,
    pub name: Option<String>,
    pub layout_type: Option<String>,
    pub master_part_path: Option<String>,
    pub show_master_shapes: bool,
    pub background: Option<ShapeFill>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_picture: Option<Box<PictureFill>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_reference: Option<StyleReference>,
    pub shapes: Vec<ShapeNode>,
    /// `p:clrMapOvr/a:overrideClrMapping`; absent when the master map applies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color_map_override: Option<ColorMap>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SlideMaster {
    pub part_path: String,
    pub name: Option<String>,
    pub theme_part_path: Option<String>,
    pub layout_part_paths: Vec<String>,
    pub background: Option<ShapeFill>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_picture: Option<Box<PictureFill>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_reference: Option<StyleReference>,
    pub shapes: Vec<ShapeNode>,
    pub text_styles: TextStyleSet,
    /// `p:clrMap`; absent from packages serialized before it was parsed.
    #[serde(default, skip_serializing_if = "ColorMap::is_identity")]
    pub color_map: ColorMap,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemePart {
    pub part_path: String,
    pub theme: Theme,
    /// Absent from packages serialized before `a:fmtScheme` was parsed.
    #[serde(default, skip_serializing_if = "ThemeFormatScheme::is_empty")]
    pub format_scheme: ThemeFormatScheme,
    /// `a:bgFillStyleLst` picture entries, indexed as `p:bgRef` names them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_pictures: Vec<Option<PictureFill>>,
}

/// A chart part resolved against one referenced presentation theme.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartPart {
    pub part_path: String,
    pub theme_part_path: Option<String>,
    pub chart: ChartSpace,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaPart {
    pub part_path: String,
    pub content_type: String,
    #[serde(
        serialize_with = "serialize_media_bytes",
        deserialize_with = "deserialize_media_bytes"
    )]
    pub bytes: Vec<u8>,
}

/// Writes base64: a JSON integer array inflates the payload about fourfold.
fn serialize_media_bytes<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use base64::Engine as _;
    serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(bytes))
}

/// Also accepts the integer arrays written before schema 2.2.
fn deserialize_media_bytes<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use base64::Engine as _;
    use serde::de::Error as _;

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Bytes {
        Base64(String),
        Integers(Vec<u8>),
    }

    match Bytes::deserialize(deserializer)? {
        Bytes::Base64(encoded) => base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .map_err(D::Error::custom),
        Bytes::Integers(bytes) => Ok(bytes),
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum ShapeNode {
    Shape(Shape),
    Picture(Picture),
    GraphicFrame(GraphicFrame),
    Group(GroupShape),
}

impl ShapeNode {
    pub fn id(&self) -> u32 {
        match self {
            Self::Shape(shape) => shape.base.id,
            Self::Picture(picture) => picture.base.id,
            Self::GraphicFrame(frame) => frame.base.id,
            Self::Group(group) => group.base.id,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShapeBase {
    pub id: u32,
    pub name: String,
    pub description: Option<String>,
    pub hidden: bool,
    pub placeholder: Option<Placeholder>,
    pub transform: ShapeTransform,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShapeTransform {
    pub x: i64,
    pub y: i64,
    pub width: i64,
    pub height: i64,
    pub rotation_deg: f64,
    pub flip_h: bool,
    pub flip_v: bool,
    pub child_x: Option<i64>,
    pub child_y: Option<i64>,
    pub child_width: Option<i64>,
    pub child_height: Option<i64>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Placeholder {
    pub placeholder_type: Option<String>,
    pub index: Option<u32>,
    pub orientation: Option<String>,
    pub size: Option<String>,
}

/// A slide holds one of each of these, so they inherit by type: PowerPoint
/// writes a slide number as `idx="12"` over a master's `idx="4"` and still
/// draws it where the master put it (#797).
const SINGLETON_PLACEHOLDERS: [&str; 5] = ["title", "sldNum", "dt", "ftr", "hdr"];

impl Placeholder {
    /// Whether this placeholder and `other` fill the same slot, so one
    /// inherits from the other.
    pub fn matches(&self, other: &Placeholder) -> bool {
        let left_type = normalize_placeholder_type(self.placeholder_type.as_deref());
        let right_type = normalize_placeholder_type(other.placeholder_type.as_deref());
        if SINGLETON_PLACEHOLDERS.contains(&left_type)
            || SINGLETON_PLACEHOLDERS.contains(&right_type)
        {
            return left_type == right_type;
        }
        match (self.index, other.index) {
            (Some(left), Some(right)) => left == right,
            _ => left_type == right_type,
        }
    }
}

fn normalize_placeholder_type(value: Option<&str>) -> &str {
    match value.unwrap_or("body") {
        "ctrTitle" => "title",
        "obj" => "body",
        value => value,
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Shape {
    #[serde(flatten)]
    pub base: ShapeBase,
    pub geometry: String,
    #[serde(
        default = "has_preset_geometry_default",
        skip_serializing_if = "is_preset_geometry"
    )]
    pub has_preset_geometry: bool,
    /// Custom paths in shape-relative coordinates.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub paths: Vec<CustomGeometryPath>,
    /// Theme formatting and text defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<Box<ShapeStyle>>,
    #[serde(default)]
    pub adjust_values: BTreeMap<String, f64>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub use_bg_fill: bool,
    pub fill: Option<ShapeFill>,
    /// The image behind an `a:blipFill`, when the fill is a stretched picture.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub picture_fill: Option<Box<PictureFill>>,
    pub outline: Option<ShapeOutline>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effects: Option<ShapeEffects>,
    pub text: Option<TextBody>,
}

/// An `a:blipFill` on a shape: the image, and the box it stretches into.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PictureFill {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relationship_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub media_part_path: Option<String>,
    #[serde(default, skip_serializing_if = "PictureCrop::is_whole")]
    pub crop: PictureCrop,
    /// `a:stretch/a:fillRect` insets, in thousandths of a percent of the box.
    #[serde(default, skip_serializing_if = "PictureCrop::is_whole")]
    pub fill_rect: PictureCrop,
    /// `a:tile`: the picture repeats at its own size instead of stretching.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tile: Option<PictureTile>,
    /// Bitmap effects in document order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<BlipEffect>,
}

/// `a:blipFill/a:tile`. The offset, alignment and flip it can also carry are
/// not read: every tile in the corpus starts at the top left, unflipped.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PictureTile {
    /// `@sx` and `@sy` as a fraction, 1.0 for the picture's own size.
    pub scale_x: f64,
    pub scale_y: f64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomGeometryPath {
    pub commands: Vec<GeometryPathCommand>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub no_fill: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub no_stroke: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Picture {
    #[serde(flatten)]
    pub base: ShapeBase,
    #[serde(default, skip_serializing_if = "is_false")]
    pub aspect_ratio_locked: bool,
    pub relationship_id: Option<String>,
    pub media_part_path: Option<String>,
    pub crop: PictureCrop,
    /// Bitmap effects in document order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<BlipEffect>,
    /// Mask geometry; defaults to the frame rectangle.
    #[serde(default = "rect_geometry", skip_serializing_if = "is_rect")]
    pub geometry: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub paths: Vec<CustomGeometryPath>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub adjust_values: BTreeMap<String, f64>,
    pub fill: Option<ShapeFill>,
    pub outline: Option<ShapeOutline>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shape_effects: Option<ShapeEffects>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<Box<ShapeStyle>>,
}

fn rect_geometry() -> String {
    "rect".to_owned()
}

fn is_rect(geometry: &str) -> bool {
    geometry == "rect"
}

fn has_preset_geometry_default() -> bool {
    true
}

fn is_preset_geometry(value: &bool) -> bool {
    *value
}

/// Bitmap effects with unresolved colours.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum BlipEffect {
    /// `a:biLevel`: luminance below `threshold` becomes black, the rest white.
    BiLevel { threshold: f64 },
    /// `a:grayscl`.
    Grayscale,
    /// `a:alphaModFix`: the whole bitmap drawn at `amount` opacity.
    Alpha { amount: f64 },
    /// `a:lum`: brightness and contrast, each a fraction in `-1.0..=1.0`.
    Luminance { brightness: f64, contrast: f64 },
    /// `a:duotone`: luminance interpolates between the two colours.
    Duotone {
        shadow: Option<ColorValue>,
        highlight: Option<ColorValue>,
    },
    /// Exact colour replacement.
    ColorChange {
        from: Option<ColorValue>,
        to: Option<ColorValue>,
        #[serde(
            default = "default_use_alpha",
            skip_serializing_if = "use_alpha_is_default",
            rename = "useAlpha"
        )]
        use_alpha: bool,
    },
}

fn default_use_alpha() -> bool {
    true
}

fn use_alpha_is_default(value: &bool) -> bool {
    *value
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PictureCrop {
    pub left: i32,
    pub top: i32,
    pub right: i32,
    pub bottom: i32,
}

impl PictureCrop {
    pub fn is_whole(&self) -> bool {
        *self == Self::default()
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphicFrame {
    #[serde(flatten)]
    pub base: ShapeBase,
    pub data: GraphicFrameData,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum GraphicFrameData {
    Table(Table),
    Chart {
        relationship_id: String,
        part_path: Option<String>,
    },
    Diagram {
        relationship_ids: Vec<String>,
        /// `ppt/diagrams/drawing#.xml`, the shapes PowerPoint saves beside a
        /// SmartArt graphic so a reader that cannot lay the diagram out can
        /// still draw it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        drawing_part_path: Option<String>,
    },
    Unknown {
        uri: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        picture: Option<Box<Picture>>,
    },
}

/// One `ppt/diagrams/drawing#.xml`: the shapes a SmartArt graphic resolves to.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagramDrawing {
    pub part_path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub synthesis_extent: Option<[i64; 2]>,
    pub shapes: Vec<ShapeNode>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupShape {
    #[serde(flatten)]
    pub base: ShapeBase,
    pub children: Vec<ShapeNode>,
}

/// An `a:tbl`: its column grid, table-wide properties and rows.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Table {
    /// `a:gridCol/@w`, in EMU.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub grid: Vec<i64>,
    #[serde(default, skip_serializing_if = "TableProperties::is_default")]
    pub properties: TableProperties,
    #[serde(
        default,
        serialize_with = "serialize_table_rows",
        deserialize_with = "deserialize_table_rows"
    )]
    pub rows: Vec<TableRow>,
}

/// `a:tblPr`: which style parts apply, and the style they come from.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TableProperties {
    pub first_row: bool,
    pub last_row: bool,
    pub first_col: bool,
    pub last_col: bool,
    pub band_row: bool,
    pub band_col: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style_id: Option<String>,
}

impl TableProperties {
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableRow {
    /// `a:tr/@h`, in EMU, a minimum rather than a fixed height.
    #[serde(default)]
    pub height: i64,
    pub cells: Vec<TableCell>,
}

impl TableRow {
    fn is_text_only(&self) -> bool {
        self.height == 0 && self.cells.iter().all(TableCell::is_text_only)
    }
}

/// An `a:tc`, with its `a:tcPr` anchoring and margins folded into `text`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TableCell {
    pub text: TextBody,
    #[serde(default = "unit_span", skip_serializing_if = "is_unit_span")]
    pub grid_span: u32,
    #[serde(default = "unit_span", skip_serializing_if = "is_unit_span")]
    pub row_span: u32,
    /// An `hMerge`/`vMerge` continuation: covered by an earlier origin cell.
    #[serde(default, skip_serializing_if = "is_false")]
    pub merged: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fill: Option<ShapeFill>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub picture_fill: Option<PictureFill>,
    #[serde(default, skip_serializing_if = "TableCellBorders::is_empty")]
    pub borders: TableCellBorders,
}

impl TableCell {
    pub fn from_text(text: TextBody) -> Self {
        Self {
            text,
            ..Self::default()
        }
    }

    /// Compared against a cell built from this text alone, so a field added
    /// later cannot be silently dropped by the released encoding.
    fn is_text_only(&self) -> bool {
        *self == Self::from_text(self.text.clone())
    }
}

impl Default for TableCell {
    fn default() -> Self {
        Self {
            text: TextBody::default(),
            grid_span: 1,
            row_span: 1,
            merged: false,
            fill: None,
            picture_fill: None,
            borders: TableCellBorders::default(),
        }
    }
}

/// `a:tcPr/a:lnL`, `a:lnT`, `a:lnR` and `a:lnB`.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TableCellBorders {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub left: Option<ShapeOutline>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top: Option<ShapeOutline>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub right: Option<ShapeOutline>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bottom: Option<ShapeOutline>,
}

impl TableCellBorders {
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }
}

fn unit_span() -> u32 {
    1
}

fn is_unit_span(span: &u32) -> bool {
    *span == 1
}

fn is_false(value: &bool) -> bool {
    !*value
}

/// Writes rows that hold nothing but cell text in the released encoding, so a
/// stored package keeps its bytes until a table gains geometry.
fn serialize_table_rows<S>(rows: &[TableRow], serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use serde::ser::SerializeSeq;

    if !rows.iter().all(TableRow::is_text_only) {
        return rows.serialize(serializer);
    }
    let mut sequence = serializer.serialize_seq(Some(rows.len()))?;
    for row in rows {
        let cells: Vec<_> = row.cells.iter().map(|cell| &cell.text).collect();
        sequence.serialize_element(&cells)?;
    }
    sequence.end()
}

/// Also accepts the released encoding's rows, which were bare `a:txBody` lists.
fn deserialize_table_rows<'de, D>(deserializer: D) -> Result<Vec<TableRow>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Row {
        Modern(TableRow),
        Legacy(Vec<TextBody>),
    }

    Ok(Vec::<Row>::deserialize(deserializer)?
        .into_iter()
        .map(|row| match row {
            Row::Modern(row) => row,
            Row::Legacy(cells) => TableRow {
                height: 0,
                cells: cells.into_iter().map(TableCell::from_text).collect(),
            },
        })
        .collect())
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextBody {
    pub anchor: Option<String>,
    pub vertical: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub num_col: Option<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spc_col: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rtl_col: Option<bool>,
    /// Use a 1.2 em percentage pitch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compat_line_spacing: Option<bool>,
    /// `a:bodyPr/@spcFirstLastPara`: honour the first paragraph's space-before
    /// and the last one's space-after.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_first_last_para: Option<bool>,
    pub autofit: Option<TextAutofit>,
    /// `a:bodyPr/@wrap`: `false` for `none`, which lays every paragraph on one
    /// line and lets it run past the shape.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wrap: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vertical_overflow: Option<TextOverflow>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub horizontal_overflow: Option<TextOverflow>,
    pub inset_left: Option<i64>,
    pub inset_top: Option<i64>,
    pub inset_right: Option<i64>,
    pub inset_bottom: Option<i64>,
    /// List properties by outline level.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub list_style: Vec<ParagraphProperties>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_list_style: Option<Box<ParagraphProperties>>,
    pub paragraphs: Vec<TextParagraph>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TextOverflow {
    Overflow,
    Clip,
    Ellipsis,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum TextAutofit {
    None,
    Shape,
    Normal {
        font_scale: Option<f64>,
        line_space_reduction: Option<f64>,
    },
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextParagraph {
    pub properties: ParagraphProperties,
    pub runs: Vec<TextRun>,
    pub end_properties: Option<RunProperties>,
}

/// A spacing height, as a share of the text size or in points.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum LineSpacing {
    Percent { value: f64 },
    Points { value: f64 },
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ParagraphProperties {
    pub alignment: Option<String>,
    pub level: u32,
    pub margin_left: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub margin_right: Option<i64>,
    pub indent: Option<i64>,
    pub bullet: Option<Bullet>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_spacing: Option<LineSpacing>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_before: Option<LineSpacing>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_after: Option<LineSpacing>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bullet_font: Option<BulletFont>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bullet_color: Option<BulletColor>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bullet_size: Option<BulletSize>,
    /// `a:pPr/@defTabSz` in EMU: the pitch of the implicit tab stops.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_tab_size: Option<i64>,
    /// `a:pPr/a:tabLst` positions in EMU. A declared empty list clears the
    /// stops the list style would otherwise contribute.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tab_stops: Option<Vec<i64>>,
    /// `a:pPr/@rtl`: the paragraph reads right to left.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rtl: Option<bool>,
    pub default_run: Option<RunProperties>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub enum BulletFont {
    FollowText,
    Typeface(String),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub enum BulletColor {
    FollowText,
    Color(ColorValue),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub enum BulletSize {
    FollowText,
    Percent(f64),
    Points(f64),
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum Bullet {
    Character {
        value: String,
    },
    AutoNumber {
        scheme: String,
        start_at: u32,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        restart: bool,
    },
    None,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextRun {
    pub text: String,
    pub properties: RunProperties,
    pub field_id: Option<String>,
    pub field_type: Option<String>,
    pub line_break: bool,
}

/// `a:rPr/@cap`: how a run is cased when drawn. Display only — the stored text
/// keeps the author's casing.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TextCaps {
    None,
    Small,
    All,
}

impl TextCaps {
    pub fn from_attribute(value: &str) -> Option<Self> {
        match value {
            "none" => Some(Self::None),
            "small" => Some(Self::Small),
            "all" => Some(Self::All),
            _ => None,
        }
    }

    pub fn as_attribute(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Small => "small",
            Self::All => "all",
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RunProperties {
    pub font_size_pt: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spacing_pt: Option<f64>,
    /// Baseline shift as a percentage of the font size; negative is subscript.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub baseline_pct: Option<f64>,
    /// `kern`: the smallest size, in points, the text is kerned at; `0` turns
    /// kerning off.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kern_pt: Option<f64>,
    pub bold: Option<bool>,
    pub italic: Option<bool>,
    pub underline: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub caps: Option<TextCaps>,
    pub font_family: Option<String>,
    pub color: Option<ColorValue>,
    pub language: Option<String>,
    pub hyperlink_relationship_id: Option<String>,
    /// `a:rPr/a:effectLst`: the shadow PowerPoint draws behind the glyphs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effects: Option<ShapeEffects>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TextStyleSet {
    pub title: Vec<ParagraphProperties>,
    pub body: Vec<ParagraphProperties>,
    pub other: Vec<ParagraphProperties>,
}