f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! The parts besides the main document part that the comments and the images change or add:
//! the relationships of the main document part, the content types, the comments part and the
//! picture files, with the IDs that the new comments, relationships and drawings take.
//!
//! A new element goes last in its part's root element, so that it changes no byte of the part
//! before it; a new part comes with its relationship and its content type. The relationship
//! types take the base of the package's own relationship of the main document, Transitional or
//! Strict (ECMA-376 Part 1, 9.1, and the Strict namespaces of Part 1, 8.1).

use std::collections::HashSet;
use std::fmt::Write as _;

use f_office_opc::{Package, Relationship, relationships_part};
use f_office_xml::{Document, Limits as XmlLimits, NodeId};

use super::build::{escaped, insert_last, run_text};
use super::{ImageFile, NamedError, NamedFault, NewPart, Splice};
use crate::ns::{self, W, WP};

/// The relationships namespace of the Open Packaging Conventions (ECMA-376 Part 2, 9.3).
const RELATIONSHIPS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";

/// The name of the content types part (ECMA-376 Part 2, 10.1.2).
const CONTENT_TYPES: &str = "[Content_Types].xml";

/// The content type of a relationships part (ECMA-376 Part 2, 9.3).
const RELATIONSHIPS_TYPE: &str = "application/vnd.openxmlformats-package.relationships+xml";

/// The content type of a comments part (ECMA-376 Part 1, 11.3.2).
const COMMENTS_TYPE: &str =
    "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml";

/// The end of the type of the package relationship of the main document part, after the base
/// that the other relationship types share.
const OFFICE_DOCUMENT: &str = "officeDocument";

/// The base of the Transitional relationship types (ECMA-376 Part 1, 15.2).
const TRANSITIONAL_TYPES: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";

/// The start of the Strict namespaces and relationship types.
const STRICT: &str = "http://purl.oclc.org/ooxml/";

/// The relationship type of a comments part, after the base.
const COMMENTS: &str = "comments";

/// The relationship type of an image, after the base.
const IMAGE: &str = "image";

/// The start of the name of a new relationship ID.
const RELATIONSHIP_ID: &str = "rId";

/// A new comment: the index of its edit, its ID, its author and its text.
struct NewComment {
    edit: usize,
    id: i64,
    author: String,
    text: String,
}

/// A new relationship of the main document part: the index of its edit, its ID, its type after
/// the base, and its target relative to the main document part.
struct NewRelationship {
    edit: usize,
    id: String,
    kind: &'static str,
    target: String,
}

/// The comments part: the one that the main document part has, or a new one.
enum CommentsPart {
    /// The part that the main document part's relationship names, with its bytes.
    Held { name: String, bytes: Vec<u8> },
    /// A new part of this name.
    New { name: String },
}

/// What the comments and the images of a list add to the parts besides the main document part.
pub(super) struct Additions<'a> {
    package: &'a Package,
    limits: &'a XmlLimits,
    /// The main document part's name.
    main: &'a str,
    /// The folder of the main document part, with its `/` at the end, or empty.
    folder: String,
    /// The base of the package's relationship types.
    types: String,
    /// Whether the package is Strict, whose new XML takes the Strict namespaces.
    strict: bool,
    relationships: Vec<NewRelationship>,
    taken_ids: HashSet<String>,
    /// The new defaults of the content types: the index of the edit, the extension and the type.
    defaults: Vec<(usize, &'static str, &'static str)>,
    /// The new overrides of the content types: the index of the edit, the part and the type.
    overrides: Vec<(usize, String, &'static str)>,
    comments: Vec<NewComment>,
    comments_part: Option<CommentsPart>,
    next_comment: Option<i64>,
    next_drawing: Option<u64>,
    pictures: Vec<NewPart>,
}

impl<'a> Additions<'a> {
    /// The additions of a list whose main document part is `main`.
    pub(super) fn new(package: &'a Package, main: &'a str, limits: &'a XmlLimits) -> Self {
        let types = package
            .relationships("")
            .ok()
            .and_then(|part| Relationship::by_type(&part.relationships, "/officeDocument"))
            .and_then(|rel| rel.rel_type.strip_suffix(OFFICE_DOCUMENT))
            .unwrap_or(TRANSITIONAL_TYPES)
            .to_owned();
        let taken_ids = package.relationships(main).map_or_default(|part| {
            part.relationships
                .iter()
                .map(|rel| rel.id.clone())
                .collect()
        });
        Self {
            package,
            limits,
            main,
            folder: main
                .rfind('/')
                .map_or_else(String::new, |at| main[..=at].to_owned()),
            strict: types.starts_with(STRICT),
            types,
            relationships: Vec::new(),
            taken_ids,
            defaults: Vec::new(),
            overrides: Vec::new(),
            comments: Vec::new(),
            comments_part: None,
            next_comment: None,
            next_drawing: None,
            pictures: Vec::new(),
        }
    }

    /// The namespace URI that new XML of the package writes for the Transitional namespace
    /// `namespace`: its Strict spelling in a Strict package.
    pub(super) fn namespace(&self, namespace: &'static str) -> &'static str {
        if !self.strict {
            return namespace;
        }
        ns::STRICT_ALIASES
            .iter()
            .find(|(_, transitional)| *transitional == namespace)
            .map_or(namespace, |(strict, _)| strict)
    }

    /// Adds the comment of the edit `edit` by `author` with `text`, and gives its ID: one more
    /// than the largest ID of the comments part and of the comment marks of `main`, the main
    /// document part.
    pub(super) fn comment(
        &mut self,
        edit: usize,
        main: &Document,
        (author, text): (&str, &str),
    ) -> Result<i64, NamedFault> {
        if self.comments_part.is_none() {
            self.comments_part = Some(self.find_comments_part(edit)?);
        }
        let id = match self.next_comment {
            Some(id) => id,
            None => self.first_comment_id(main)?,
        };
        self.next_comment = Some(id.checked_add(1).ok_or(NamedFault::NoFreeId("comment"))?);
        self.comments.push(NewComment {
            edit,
            id,
            author: author.to_owned(),
            text: text.to_owned(),
        });
        Ok(id)
    }

    /// The comments part that the main document part has, or a new one with its relationship
    /// and its content type, for the edit `edit`.
    fn find_comments_part(&mut self, edit: usize) -> Result<CommentsPart, NamedFault> {
        let held = self
            .package
            .relationships(self.main)
            .ok()
            .and_then(|part| Relationship::by_type(&part.relationships, ns::REL_COMMENTS))
            .filter(|rel| !rel.external)
            .map(|rel| rel.target.clone());
        if let Some(name) = held {
            let bytes = self
                .package
                .part(&name)
                .ok_or_else(|| NamedFault::Part {
                    part: name.clone(),
                    why: "the package does not hold it".to_owned(),
                })?
                .to_vec();
            return Ok(CommentsPart::Held { name, bytes });
        }
        let name = self.unused_name("comments", ".xml");
        self.relationship(edit, COMMENTS, &name);
        self.overrides
            .push((edit, format!("/{name}"), COMMENTS_TYPE));
        Ok(CommentsPart::New { name })
    }

    /// One more than the largest comment ID of the comments part and of `main`, or 0.
    fn first_comment_id(&self, main: &Document) -> Result<i64, NamedFault> {
        let mut largest: Option<i64> = None;
        let mut take = |doc: &Document, locals: &[&str]| {
            for node in elements(doc) {
                if locals.iter().any(|local| doc.is(node, W, local))
                    && let Some(id) = doc
                        .attribute(node, Some(W), "id")
                        .and_then(|id| id.trim().parse::<i64>().ok())
                {
                    largest = Some(largest.map_or(id, |seen| seen.max(id)));
                }
            }
        };
        take(
            main,
            &["commentRangeStart", "commentRangeEnd", "commentReference"],
        );
        if let Some(CommentsPart::Held { name, bytes }) = &self.comments_part {
            let doc = self.parse(name, bytes)?;
            take(&doc, &["comment"]);
        }
        largest.map_or(Ok(0), |id| {
            id.checked_add(1).ok_or(NamedFault::NoFreeId("comment"))
        })
    }

    /// Adds the picture file of the edit `edit`, with its relationship and its content type,
    /// and gives the relationship's ID, the ID of its drawing and the file's name.
    pub(super) fn picture(
        &mut self,
        edit: usize,
        main: &Document,
        image: &ImageFile,
    ) -> Result<(String, u64, String), NamedFault> {
        let (extension, content_type) = image.extension_and_type();
        let name = self.unused_name("media/image", &format!(".{extension}"));
        let target = name
            .strip_prefix(self.folder.as_str())
            .unwrap_or(&name)
            .to_owned();
        let id = self.relationship(edit, IMAGE, &name);
        if !self
            .defaults
            .iter()
            .any(|(_, known, _)| *known == extension)
        {
            self.defaults.push((edit, extension, content_type));
        }
        let drawing = match self.next_drawing {
            Some(id) => id,
            None => self.first_drawing_id(main),
        };
        self.next_drawing = Some(
            drawing
                .checked_add(1)
                .ok_or(NamedFault::NoFreeId("drawing"))?,
        );
        self.pictures.push(NewPart {
            edit,
            name,
            data: image.data().to_vec(),
        });
        let file = target.rsplit('/').next().unwrap_or(&target).to_owned();
        Ok((id, drawing, file))
    }

    /// One more than the largest drawing ID (`wp:docPr`) of the main document part `main` and
    /// of the parts that its relationships name, or 1.
    fn first_drawing_id(&self, main: &Document) -> u64 {
        let mut largest = drawing_ids(main).max();
        let related: Vec<String> = self
            .package
            .relationships(self.main)
            .map_or_default(|part| {
                part.relationships
                    .iter()
                    .filter(|rel| !rel.external && is_xml_name(&rel.target))
                    .map(|rel| rel.target.clone())
                    .collect()
            });
        for name in related {
            let parsed = self.package.part(&name).and_then(|bytes| {
                Document::parse_with_aliases(bytes, self.limits, ns::STRICT_ALIASES).ok()
            });
            if let Some(doc) = parsed {
                largest = largest.max(drawing_ids(&doc).max());
            }
        }
        largest.map_or(1, |id| id.saturating_add(1))
    }

    /// Adds a relationship of the main document part of the type `kind` after the base to the
    /// part `name`, for the edit `edit`, and gives its new ID: `rId` and the first number from
    /// one more than the count of the IDs that the part and the list take that no ID takes.
    fn relationship(&mut self, edit: usize, kind: &'static str, name: &str) -> String {
        let mut number = self.taken_ids.len() + 1;
        let id = loop {
            let id = format!("{RELATIONSHIP_ID}{number}");
            if !self.taken_ids.contains(&id) {
                break id;
            }
            number += 1;
        };
        self.taken_ids.insert(id.clone());
        let target = name
            .strip_prefix(self.folder.as_str())
            .unwrap_or(name)
            .to_owned();
        self.relationships.push(NewRelationship {
            edit,
            id: id.clone(),
            kind,
            target,
        });
        id
    }

    /// The first name `{folder}{stem}{N}{extension}`, or `{folder}{stem}{extension}` for a
    /// comments part, that the package does not hold and that no new part of the list takes.
    /// The package and the list hold fewer parts than numbers, so one is free.
    fn unused_name(&self, stem: &str, extension: &str) -> String {
        let taken = |name: &str| {
            self.package.part_name(name).is_some()
                || self
                    .pictures
                    .iter()
                    .any(|part| part.name.eq_ignore_ascii_case(name))
        };
        let plain = format!("{}{stem}{extension}", self.folder);
        if stem == "comments" && !taken(&plain) {
            return plain;
        }
        let names = self.package.part_names().count() + self.pictures.len() + 1;
        (1..=names)
            .map(|number| format!("{}{stem}{number}{extension}", self.folder))
            .find(|name| !taken(name))
            .unwrap_or(plain)
    }

    /// The part `name`, parsed.
    fn parse(&self, name: &str, bytes: &[u8]) -> Result<Document, NamedFault> {
        Document::parse(bytes, self.limits).map_err(|error| NamedFault::Part {
            part: name.to_owned(),
            why: error.to_string(),
        })
    }

    /// The splices of the parts besides the main document part, and the new parts.
    pub(super) fn finish(self) -> Result<Changes, NamedError> {
        let mut splices = Vec::new();
        let mut parts = Vec::new();
        self.finish_comments(&mut splices, &mut parts)?;
        let new_relationships = self.finish_relationships(&mut splices, &mut parts)?;
        self.finish_content_types(&mut splices, new_relationships)?;
        parts.extend(self.pictures);
        Ok((splices, parts))
    }

    fn finish_comments(
        &self,
        splices: &mut Vec<(String, Splice)>,
        parts: &mut Vec<NewPart>,
    ) -> Result<(), NamedError> {
        let Some(first) = self.comments.first().map(|comment| comment.edit) else {
            return Ok(());
        };
        let at = fault_at(first);
        match &self.comments_part {
            Some(CommentsPart::Held { name, bytes }) => {
                let doc = self.parse(name, bytes).map_err(at)?;
                let (root, w) = root_and_prefix(&doc, name).map_err(at)?;
                let w = w.ok_or(NamedFault::NoPrefix).map_err(at)?;
                let xml: String = self.comments.iter().map(|c| comment_xml(&w, c)).collect();
                let span = doc
                    .span(root)
                    .map_err(|error| at(part_fault(name, &error)))?;
                let (range, xml) = insert_last(bytes, span, &xml);
                splices.push((
                    name.clone(),
                    Splice {
                        edit: first,
                        range,
                        xml,
                    },
                ));
            }
            Some(CommentsPart::New { name }) => {
                let xml: String = self.comments.iter().map(|c| comment_xml("w", c)).collect();
                parts.push(NewPart {
                    edit: first,
                    name: name.clone(),
                    data: format!(
                        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>{}<w:comments xmlns:w="{}">{xml}</w:comments>"#,
                        "\r\n",
                        self.namespace(W)
                    )
                    .into_bytes(),
                });
            }
            None => {}
        }
        Ok(())
    }

    /// Adds the new relationships, and gives the index of the edit that made a new
    /// relationships part, if one did.
    fn finish_relationships(
        &self,
        splices: &mut Vec<(String, Splice)>,
        parts: &mut Vec<NewPart>,
    ) -> Result<Option<usize>, NamedError> {
        let Some(first) = self.relationships.first().map(|rel| rel.edit) else {
            return Ok(None);
        };
        let at = fault_at(first);
        let held = self
            .package
            .relationships(self.main)
            .map_or_default(|part| part.name.clone());
        let element = |prefix: &Option<String>, rel: &NewRelationship| {
            let name = qualified(prefix.as_deref(), "Relationship");
            format!(
                r#"<{name} Id="{}" Type="{}{}" Target="{}"/>"#,
                escaped(&rel.id),
                escaped(&self.types),
                rel.kind,
                escaped(&rel.target)
            )
        };
        if held.is_empty() {
            let name = relationships_part(self.main);
            let xml: String = self
                .relationships
                .iter()
                .map(|rel| element(&None, rel))
                .collect();
            parts.push(NewPart {
                edit: first,
                name,
                data: format!(
                    r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>{}<Relationships xmlns="{RELATIONSHIPS}">{xml}</Relationships>"#,
                    "\r\n"
                )
                .into_bytes(),
            });
            return Ok(Some(first));
        }
        let bytes = self.package.part(&held).ok_or_else(|| {
            at(NamedFault::Part {
                part: held.clone(),
                why: "the package does not hold it".to_owned(),
            })
        })?;
        let doc = self.parse(&held, bytes).map_err(at)?;
        let (root, prefix) = root_and_prefix(&doc, &held).map_err(at)?;
        let xml: String = self
            .relationships
            .iter()
            .map(|rel| element(&prefix, rel))
            .collect();
        let span = doc
            .span(root)
            .map_err(|error| at(part_fault(&held, &error)))?;
        let (range, xml) = insert_last(bytes, span, &xml);
        splices.push((
            held,
            Splice {
                edit: first,
                range,
                xml,
            },
        ));
        Ok(None)
    }

    /// Adds the new content types: a default for each new extension, and for a new
    /// relationships part, of the edit `new_relationships`; an override for a new comments part.
    fn finish_content_types(
        &self,
        splices: &mut Vec<(String, Splice)>,
        new_relationships: Option<usize>,
    ) -> Result<(), NamedError> {
        let first = self
            .defaults
            .iter()
            .map(|(edit, _, _)| *edit)
            .chain(self.overrides.iter().map(|(edit, _, _)| *edit))
            .chain(new_relationships)
            .min();
        let Some(first) = first else {
            return Ok(());
        };
        let at = fault_at(first);
        let name = self
            .package
            .part_name(CONTENT_TYPES)
            .ok_or_else(|| {
                at(NamedFault::Part {
                    part: CONTENT_TYPES.to_owned(),
                    why: "the package does not hold it".to_owned(),
                })
            })?
            .to_owned();
        let bytes = self.package.part(&name).unwrap_or_default();
        let doc = self.parse(&name, bytes).map_err(at)?;
        let (root, prefix) = root_and_prefix(&doc, &name).map_err(at)?;
        let held: Vec<String> = doc
            .child_elements(root)
            .filter_map(|node| doc.attribute(node, None, "Extension"))
            .map(str::to_ascii_lowercase)
            .collect();
        let mut defaults: Vec<(&str, &str)> = self
            .defaults
            .iter()
            .map(|(_, extension, kind)| (*extension, *kind))
            .collect();
        if new_relationships.is_some() {
            defaults.push(("rels", RELATIONSHIPS_TYPE));
        }
        let default = qualified(prefix.as_deref(), "Default");
        let mut xml = String::new();
        for (extension, kind) in defaults
            .iter()
            .filter(|(extension, _)| !held.iter().any(|known| known == extension))
        {
            let _ = write!(
                xml,
                r#"<{default} Extension="{extension}" ContentType="{kind}"/>"#
            );
        }
        let overriding = qualified(prefix.as_deref(), "Override");
        for (_, part, kind) in &self.overrides {
            let _ = write!(
                xml,
                r#"<{overriding} PartName="{}" ContentType="{kind}"/>"#,
                escaped(part)
            );
        }
        if xml.is_empty() {
            return Ok(());
        }
        let span = doc
            .span(root)
            .map_err(|error| at(part_fault(&name, &error)))?;
        let (range, xml) = insert_last(bytes, span, &xml);
        splices.push((
            name,
            Splice {
                edit: first,
                range,
                xml,
            },
        ));
        Ok(())
    }
}

/// The splices of the other parts, each with its part's name, and the new parts.
type Changes = (Vec<(String, Splice)>, Vec<NewPart>);

/// The error of a fault for the edit `edit`, the first edit that the part changes.
fn fault_at(edit: usize) -> impl Fn(NamedFault) -> NamedError + Copy {
    move |fault| NamedError {
        edit: Some(edit),
        fault,
    }
}

/// The XML of a new comment with the prefix `w`: one paragraph with the comment's mark and its
/// text (ECMA-376 Part 1, 17.13.4.2).
fn comment_xml(w: &str, comment: &NewComment) -> String {
    let text = if comment.text.is_empty() {
        String::new()
    } else {
        format!("<{w}:r>{}</{w}:r>", run_text(w, &comment.text))
    };
    format!(
        r#"<{w}:comment {w}:id="{}" {w}:author="{}"><{w}:p><{w}:r><{w}:annotationRef/></{w}:r>{text}</{w}:p></{w}:comment>"#,
        comment.id,
        escaped(&comment.author)
    )
}

/// The root element of the part `name` and its prefix.
fn root_and_prefix(doc: &Document, name: &str) -> Result<(NodeId, Option<String>), NamedFault> {
    let root = doc.root().map_err(|error| part_fault(name, &error))?;
    let prefix = doc
        .element(root)
        .and_then(|element| element.name.prefix.map(str::to_owned));
    Ok((root, prefix))
}

/// The fault of the part `name` that does not read.
fn part_fault(name: &str, error: &f_office_xml::Error) -> NamedFault {
    NamedFault::Part {
        part: name.to_owned(),
        why: error.to_string(),
    }
}

/// The name `local` with `prefix`, if any.
fn qualified(prefix: Option<&str>, local: &str) -> String {
    prefix.map_or_else(|| local.to_owned(), |prefix| format!("{prefix}:{local}"))
}

/// Whether the part `name` is an XML part by its extension.
fn is_xml_name(name: &str) -> bool {
    name.rsplit_once('.')
        .is_some_and(|(_, extension)| extension.eq_ignore_ascii_case("xml"))
}

/// Every element of `doc`.
fn elements(doc: &Document) -> Vec<NodeId> {
    let mut found = Vec::new();
    let mut stack: Vec<NodeId> = doc.root().into_iter().collect();
    while let Some(node) = stack.pop() {
        found.push(node);
        stack.extend(doc.child_elements(node));
    }
    found
}

/// The IDs of the drawings (`wp:docPr`) of `doc`.
fn drawing_ids(doc: &Document) -> impl Iterator<Item = u64> + '_ {
    elements(doc)
        .into_iter()
        .filter(|&node| doc.is(node, WP, "docPr"))
        .filter_map(|node| doc.attribute(node, None, "id"))
        .filter_map(|id| id.trim().parse::<u64>().ok())
}