acorn-lib 0.1.59

ACORN library
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
//! ## OOXML data structures
//!
//! Data structures for modeling [`OOXML`].
//!
//! [`OOXML`]: https://en.wikipedia.org/wiki/Office_Open_XML
use crate::io::{read_file, ApiResult};
use crate::prelude::PathBuf;
use crate::util::{Label, StringConversion};
use bon::Builder;
use color_eyre::eyre::eyre;
use core::fmt;
use core::iter::once;
use core::str::from_utf8;
use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, Writer};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use tracing::{debug, error};

const XML_DECLARATION: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
/// Trait for working with OOXML data structures
pub trait XmlRels {
    /// Get the largest revision identifier
    fn largest_revision_identifier(&self) -> Option<u32> {
        None
    }
    /// Get all revision identifiers
    fn revision_identifiers(&self) -> Vec<u32> {
        vec![]
    }
}
/// OOXML Text Capitalization Type
///
/// See <https://datypic.com/sc/ooxml/t-a_ST_TextCapsType.html>
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Capitalization {
    /// No capitalization
    #[default]
    #[serde(rename = "none")]
    NoCap,
    /// All capitalized
    All,
    /// Small caps
    Small,
}
/// OOXML Text Effect
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Effect {
    /// See <https://datypic.com/sc/ooxml/e-a_blur-1.html>
    #[serde(rename(serialize = "a:blur", deserialize = "blur"))]
    Blur {
        /// Blur radius
        #[serde(rename = "@rad")]
        radius: Option<String>,
        /// Grow bounds
        #[serde(rename = "@grow")]
        grow_bounds: Option<String>,
    },
    /// See <https://datypic.com/sc/ooxml/e-a_glow-1.html>
    #[serde(rename(serialize = "a:glow", deserialize = "glow"))]
    Glow,
    /// See <https://datypic.com/sc/ooxml/e-a_reflection-1.html>
    #[serde(rename(serialize = "a:reflection", deserialize = "reflection"))]
    Reflection,
}
/// OOXML Line fill properties
///
/// See <https://datypic.com/sc/ooxml/g-a_EG_LineFillProperties.html>
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum LineFill {
    /// No fill
    #[default]
    #[serde(rename(serialize = "a:noFill", deserialize = "noFill"))]
    NoFill,
    /// Solid fill
    #[serde(rename(serialize = "a:solidFill", deserialize = "solidFill"))]
    Solid,
    /// Gradient fill
    #[serde(rename(serialize = "a:gradFill", deserialize = "gradFill"))]
    Gradient,
    /// Pattern fill
    #[serde(rename(serialize = "a:pattFill", deserialize = "pattFill"))]
    Pattern,
}
/// OOXML Text Strike Type
///
/// See <https://datypic.com/sc/ooxml/t-a_ST_TextStrikeType.html>
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Strikethrough {
    /// No strike
    #[default]
    #[serde(rename = "noStrike")]
    NoStrike,
    /// Single strike
    #[serde(rename = "sngStrike")]
    Single,
    /// Double strike
    #[serde(rename = "dblStrike")]
    Double,
}
/// OOXML Text Underline Type
///
/// See <https://datypic.com/sc/ooxml/g-a_EG_TextUnderlineLine.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TextUnderline {
    /// Underline follows text
    #[serde(rename(serialize = "a:uLnTx", deserialize = "uLnTx"))]
    FollowsText,
    /// Underline stroke
    #[serde(rename(serialize = "a:uLn", deserialize = "uLn"))]
    Stroke,
}
/// OOXML Bullet Character (`a:buChar`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_buChar-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BulletCharacter {
    /// Bullet character
    #[serde(rename = "@char")]
    pub character: String,
}
/// OOXML Bullet Color (`a:buClr`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_buClr-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BulletColor {
    /// RGB color model - hex variant
    ///
    /// See <https://www.datypic.com/sc/ooxml/e-a_srgbClr-1.html>
    #[serde(rename(serialize = "a:srgbClr", deserialize = "srgbClr"))]
    pub color: Color,
}
/// OOXML Bullet Font (`a:buFont`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_buFont-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BulletFont {
    /// Text typeface
    #[serde(rename = "@typeface")]
    pub typeface: String,
    /// Panose setting
    ///
    /// See <https://en.wikipedia.org/wiki/PANOSE>
    #[serde(rename = "@panose")]
    pub panose: String,
    /// Similar font family
    #[serde(rename = "@pitchFamily")]
    pub similar_font_family: String,
    /// Similar character set
    #[serde(rename = "@charset")]
    pub charset: String,
}
/// OOXML RGB Color - Hex variant (`a:srgbClr`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_srgbClr-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Color {
    /// Hex color
    #[serde(rename = "@val")]
    pub value: String,
}
/// OOXML Effect Container (`a:effectLst`)
///
/// See <https://datypic.com/sc/ooxml/e-a_effectLst-1.html>
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EffectContainer {
    /// Effects (e.g. blur, glow, etc.)
    #[serde(rename = "$value")]
    pub effect: Option<Vec<Effect>>,
}
/// OOXML Complex Script Font (`a:cs`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_cs-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FontComplexScript {
    /// Text typeface
    #[serde(rename = "@typeface")]
    pub typeface: String,
}
/// OOXML East Asian Font (`a:ea`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_ea-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FontEastAsian {
    /// Text typeface
    #[serde(rename = "@typeface")]
    pub typeface: String,
}
/// OOXML Symbol Font (`a:sym`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_sym-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FontSymbol {
    /// Text typeface
    #[serde(rename = "@typeface")]
    pub typeface: String,
}
/// OOXML Line (`a:ln`)
///
/// See <https://datypic.com/sc/ooxml/e-a_ln-5.html>
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Line {
    #[serde(rename = "$value")]
    line_fill: LineFill,
}
/// Struct for parsing OOXML relationships from .rel files
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
#[builder(start_fn = init)]
pub struct Relationships {
    /// List of relationships
    #[builder(default = vec![])]
    pub relationship: Vec<Relationship>,
    /// XML Namespace
    #[builder(default = "http://schemas.openxmlformats.org/package/2006/relationships".to_string())]
    #[serde(rename = "@xmlns")]
    pub namespace: String,
}
/// Relationships describe references from parts to other internal resources in the package or to external resources
///
/// See <https://ooxml.info/docs/9/9.2/>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
#[builder(start_fn = init)]
pub struct Relationship {
    /// Relationship identifier
    #[serde(rename = "@Id")]
    pub id: String,
    /// Relationship type
    #[builder(default = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide".to_string())]
    #[serde(rename = "@Type")]
    pub relationship_type: String,
    /// Target resource identifier
    #[serde(rename = "@Target")]
    pub target: String,
    /// Target mode
    #[serde(rename = "@TargetMode")]
    pub target_mode: Option<String>,
}
/// Root element of a PowerPoint `presentation.xml` document.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename = "p:presentation")]
pub struct Presentation {
    /// Slide identifier list.
    #[serde(rename = "p:sldIdLst")]
    pub slide_id_list: Option<SlideIdList>,
}
/// List of PowerPoint slide identifiers.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SlideIdList {
    /// Slide identifiers.
    #[serde(rename = "p:sldId")]
    pub slide_ids: Vec<SlideId>,
}
/// PowerPoint slide identifier entry.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SlideId {
    /// Slide identifier.
    #[serde(rename = "@id")]
    pub id: u32,
    /// Relationship identifier.
    #[serde(rename = "@r:id")]
    pub relationship_id: String,
}
/// OOXML Text Character Properties (`a:rPr`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_rPr-2.html>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[builder(start_fn = init)]
pub struct TextCharacterProperties {
    /// Baseline
    #[serde(rename = "@baseline")]
    pub baseline: Option<String>,
    /// Bold
    #[serde(rename = "@b")]
    pub bold: Option<String>,
    /// Text capitalization type
    #[serde(rename = "@cap")]
    pub capitalization: Option<Capitalization>,
    /// Dirty
    #[builder(default = "0".to_string())]
    #[serde(rename = "@dirty")]
    pub dirty: String,
    /// Italic
    #[serde(rename = "@i")]
    pub italic: Option<String>,
    /// Kerning
    #[builder(default = "0".to_string())]
    #[serde(rename = "@kern")]
    pub kerning: String,
    /// Kumimoji
    #[serde(rename = "@kumimoji")]
    pub kumimoji: Option<String>,
    /// Language identifier
    #[serde(rename = "@lang")]
    pub language: Option<String>,
    /// No proofing
    #[serde(rename = "@noProof")]
    pub no_proofing: Option<String>,
    /// Normalized heights
    #[serde(rename = "@normalizeH")]
    pub normalize_heights: Option<String>,
    /// Spacing
    #[serde(rename = "@spc")]
    pub spacing: Option<String>,
    /// Font size
    #[serde(rename = "@sz")]
    pub size: Option<String>,
    /// Strikethrough
    #[serde(rename = "@strike")]
    pub strikethrough: Option<Strikethrough>,
    /// Underline
    #[serde(rename = "@u")]
    pub underline: Option<String>,
    /// OOXML Line (`a:ln`)
    ///
    /// See <https://www.datypic.com/sc/ooxml/e-a_ln-5.html>
    #[serde(rename(serialize = "a:ln", deserialize = "ln"))]
    pub line: Option<Line>,
    /// Effect list
    #[serde(rename(serialize = "a:effectlst", deserialize = "effectLst"))]
    pub effect_list: Option<EffectContainer>,
    /// Underline follows text
    #[serde(rename(serialize = "a:uLnTx", deserialize = "uLnTx"))]
    pub underline_follows_text: Option<UnderlineFollowsText>,
    /// Underline stroke
    #[serde(rename(serialize = "a:uLn", deserialize = "uLn"))]
    pub underline_stroke: Option<UnderlineStroke>,
    /// Underline fill properties follow text
    #[serde(rename(serialize = "a:uFillTx", deserialize = "uFillTx"))]
    pub underline_fill_properties_follow_text: Option<UnderlineFillPropertiesFollowText>,
    /// Underline fill
    #[serde(rename(serialize = "a:uFill", deserialize = "uFill"))]
    pub underline_fill: Option<UnderlineFill>,
    /// Complext script font
    #[serde(rename(serialize = "a:cs", deserialize = "cs"))]
    pub font_complex_script: Option<FontComplexScript>,
    /// East Asian font
    #[serde(rename(serialize = "a:ea", deserialize = "ea"))]
    pub font_east_asian: Option<FontEastAsian>,
    /// Symbol font
    #[serde(rename(serialize = "a:sym", deserialize = "sym"))]
    pub font_symbol: Option<FontSymbol>,
}
/// OOXML Text Paragraph (`a:p`)
///
/// See <https://datypic.com/sc/ooxml/e-a_p-1.html>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[builder(start_fn = init)]
#[serde(rename = "a:p")]
pub struct TextParagraph {
    /// Text paragraph properties
    #[builder(default = Vec::new())]
    #[serde(rename(serialize = "a:pPr", deserialize = "pPr"))]
    pub text_paragraph_properties: Vec<TextParagraphProperties>,
    /// Text runs
    #[builder(default = Vec::new())]
    #[serde(rename(serialize = "a:r", deserialize = "r"))]
    pub text_run: Vec<TextRun>,
    /// OOXML End Paragraph Run Properties (`a:endParaRPr`)
    ///
    /// See <https://datypic.com/sc/ooxml/e-a_endParaRPr-1.html>
    #[serde(rename(serialize = "a:endParaRPr", deserialize = "endParaRPr"))]
    pub end_paragraph_run_properties: Option<TextCharacterProperties>,
}
/// OOXML Text Paragraph Properties (`a:pPr`)
///
/// See <https://datypic.com/sc/ooxml/e-a_pPr-1.html>
#[skip_serializing_none]
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[builder(start_fn = init)]
pub struct TextParagraphProperties {
    /// Indent
    #[serde(rename = "@indent")]
    #[builder(default = "0".to_string())]
    pub indent: String,
    /// Left margin
    #[serde(rename = "@marL")]
    #[builder(default = "0".to_string())]
    pub margin_left: String,
    /// Bullet color
    #[serde(rename(serialize = "a:buClr", deserialize = "buClr"))]
    pub bullet_color: Option<BulletColor>,
    /// Bullet font
    #[serde(rename(serialize = "a:buFont", deserialize = "buFont"))]
    pub bullet_font: Option<BulletFont>,
    /// Bullet character
    #[serde(rename(serialize = "a:buChar", deserialize = "buChar"))]
    pub bullet_character: Option<BulletCharacter>,
    /// Default text run properties
    #[serde(rename(serialize = "a:defRPr", deserialize = "defRPr"))]
    pub default_text_run_properties: Option<TextRunPropertiesDefault>,
}
/// OOXML Text Run (`a:r`)
///
/// See <https://datypic.com/sc/ooxml/e-a_r-1.html>
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[builder(start_fn = init)]
pub struct TextRun {
    /// Text run properties
    #[builder(default = Vec::new())]
    #[serde(rename(serialize = "a:rPr", deserialize = "rPr"))]
    pub text_run_properties: Vec<TextCharacterProperties>,
    /// Text
    #[builder(default = TextString::init().build())]
    #[serde(rename(serialize = "a:t", deserialize = "t"))]
    pub text: TextString,
}
/// OOXML Default Text Run Properties (`a:defRpr`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_defRPr-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TextRunPropertiesDefault {}
/// OOXML Text String (`a:t`)
///
/// See <https://datypic.com/sc/ooxml/e-a_t-1.html>
#[derive(Builder, Clone, Debug, Deserialize, Serialize)]
#[builder(start_fn = init)]
pub struct TextString {
    /// Text value
    #[builder(default = "".to_string())]
    #[serde(rename = "$text")]
    pub value: String,
}
/// OOXML Underline Fill (`a:uFill`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_uFill-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UnderlineFill {}
/// OOXML Underline Fill Properties Follow Text (`a:uFillTx`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_uFillTx-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UnderlineFillPropertiesFollowText {}
/// OOXML Underline Follows Text (`a:uLnTx`)
///
/// See <https://datypic.com/sc/ooxml/e-a_uLnTx-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UnderlineFollowsText {}
/// OOXML Underline Stroke (`a:uLn`)
///
/// See <https://www.datypic.com/sc/ooxml/e-a_uLn-1.html>
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UnderlineStroke {}
impl XmlRels for Vec<Relationship> {
    fn largest_revision_identifier(&self) -> Option<u32> {
        self.revision_identifiers().iter().max().cloned()
    }
    fn revision_identifiers(&self) -> Vec<u32> {
        self.clone()
            .iter()
            .filter_map(|x| x.id.clone().trim_start_matches("rId").to_string().parse::<u32>().ok())
            .collect::<Vec<u32>>()
    }
}
impl Default for Relationships {
    fn default() -> Self {
        Self::init().build()
    }
}
impl fmt::Display for Relationships {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.to_string() {
            | Ok(xml) => write!(f, "{}", xml),
            | Err(e) => write!(f, "Error serializing Relationships: {}", e),
        }
    }
}
impl Relationships {
    /// Add a relationship
    pub fn add_relationship(&self, value: Relationship) -> Relationships {
        let Relationships { relationship, .. } = self;
        let updated = relationship.clone().into_iter().chain(once(value)).collect::<Vec<_>>();
        Relationships::init().relationship(updated).build()
    }
    /// Get largest revision identifier among relationships
    pub fn largest_revision_identifier(&self) -> Option<u32> {
        self.relationship.largest_revision_identifier()
    }
    /// Convert to XML string using quick_xml serialization
    pub fn to_string(&self) -> Result<String, quick_xml::de::DeError> {
        let xml = quick_xml::se::to_string(self).map_err(|e| quick_xml::de::DeError::Custom(e.to_string()))?;
        Ok(format!("{}{}", XML_DECLARATION, xml))
    }
}
/// Add a slide identifier to a PowerPoint `presentation.xml` document.
pub fn add_slide_to_presentation_xml(xml: &str, slide_identifier: u32, revision_identifier: u32) -> ApiResult<String> {
    let mut reader = Reader::from_str(xml);
    let mut writer = Writer::new(Vec::new());
    let mut found_slide_list = false;
    loop {
        match reader.read_event() {
            | Ok(Event::End(end)) if end.name().as_ref() == b"p:sldIdLst" => {
                found_slide_list = true;
                let mut slide = BytesStart::new("p:sldId");
                let id = slide_identifier.to_string();
                let relationship_id = format!("rId{revision_identifier}");
                slide.push_attribute(("id", id.as_str()));
                slide.push_attribute(("r:id", relationship_id.as_str()));
                match writer.write_event(Event::Empty(slide)).and_then(|_| writer.write_event(Event::End(end))) {
                    | Ok(_) => {}
                    | Err(why) => break Err(eyre!("Failed to write presentation slide identifier — {why}")),
                }
            }
            | Ok(Event::Eof) if found_slide_list => {
                let output = writer.into_inner();
                match String::from_utf8(output) {
                    | Ok(value) => break Ok(value),
                    | Err(why) => break Err(eyre!("Failed to decode presentation.xml as UTF-8 — {why}")),
                }
            }
            | Ok(Event::Eof) => break Err(eyre!("Missing p:sldIdLst in presentation.xml")),
            | Ok(event) => match writer.write_event(event) {
                | Ok(_) => {}
                | Err(why) => break Err(eyre!("Failed to write presentation.xml event — {why}")),
            },
            | Err(why) => break Err(eyre!("Failed to parse presentation.xml at byte {} — {why}", reader.buffer_position())),
        }
    }
}
/// Replace a relationship target with a new media target.
pub fn update_relationship_target(content: &str, current_target: &str, target: &str) -> ApiResult<String> {
    quick_xml::de::from_str::<Relationships>(content)
        .map_err(|why| eyre!("Failed to parse slide relationships — {why}"))
        .and_then(|rels| {
            let updated = rels
                .relationship
                .into_iter()
                .map(|rel| match rel.target == current_target {
                    | true => Relationship::init()
                        .id(rel.id)
                        .relationship_type(rel.relationship_type)
                        .target(target.to_string())
                        .maybe_target_mode(rel.target_mode)
                        .build(),
                    | false => rel,
                })
                .collect::<Vec<_>>();
            Relationships::init()
                .relationship(updated)
                .build()
                .to_string()
                .map_err(|why| eyre!("Failed to serialize slide relationships — {why}"))
        })
}
/// Validate that XML content is well formed.
pub fn validate_xml_well_formed(content: &str) -> bool {
    let mut reader = Reader::from_str(content);
    match content.trim().is_empty() {
        | true => false,
        | false => {
            let mut open_elements = Vec::new();
            loop {
                match reader.read_event() {
                    | Ok(Event::Start(event)) => open_elements.push(event.name().as_ref().to_vec()),
                    | Ok(Event::End(event)) => match open_elements.pop() {
                        | Some(name) if name == event.name().as_ref() => {}
                        | _ => break false,
                    },
                    | Ok(Event::Eof) => break open_elements.is_empty(),
                    | Ok(_) => {}
                    | Err(_) => break false,
                }
            }
        }
    }
}
/// Prettify XML
pub fn prettify_xml(xml: &str) -> String {
    let mut reader = Reader::from_str(xml);
    let mut writer = Writer::new_with_indent(Vec::new(), b' ', 2);
    loop {
        match reader.read_event() {
            | Ok(Event::Eof) => break,
            | Ok(event) => match writer.write_event(event) {
                | Ok(_) => {}
                | Err(why) => {
                    error!("=> {} Cannot write XML event — {why}", Label::fail());
                    break;
                }
            },
            | Err(why) => {
                error!("=> {} Error at XML position {} — {why}", Label::fail(), reader.buffer_position());
                break;
            }
        }
    }
    let output = writer.into_inner();
    match from_utf8(&output) {
        | Ok(value) => value.to_string(),
        | Err(why) => {
            error!("=> {} Cannot decode prettified XML as UTF-8 — {why}", Label::fail());
            String::new()
        }
    }
}
/// Read OOXML relationships XML file.
pub fn read_xml_rel(path: PathBuf) -> Option<Relationships> {
    match read_file(path.clone()) {
        | Ok(content) => {
            let parsed = quick_xml::de::from_str::<Relationships>(&content);
            debug!("=> {} Relationships = {:#?}", Label::using(), parsed);
            match parsed {
                | Ok(value) => Some(value),
                | Err(why) => {
                    error!(
                        path = path.to_absolute_string(),
                        "=> {} Cannot parse relationships - {why}",
                        Label::fail()
                    );
                    None
                }
            }
        }
        | Err(why) => {
            error!(path = path.to_absolute_string(), "=> {} Cannot read xml.rels file - {why}", Label::fail());
            None
        }
    }
}