1use std::collections::{HashMap, HashSet};
21use std::fmt;
22
23use serde::{Deserialize, Serialize};
24
25use crate::admission::{AdmissionError, InputLimits};
26use crate::comments::CommentFamily;
27use crate::comparer::parts::carry_part_relationships;
28use crate::namespaces::{MC, W, W14};
29use crate::opc::{OpcError, PartFs, relative_rel_target};
30use crate::xmllinq::{Dom, NodeId, XName};
31
32const RELS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
33const XMLNS: &str = "http://www.w3.org/2000/xmlns/";
34
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum SectionBreak {
39 #[default]
42 NextPage,
43 Continuous,
46 None,
49}
50
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum AppendComments {
55 #[default]
57 Drop,
58 Carry,
62}
63
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(default)]
67pub struct AppendOptions {
68 pub section_break: SectionBreak,
70 pub keep_sections: bool,
73 pub comments: AppendComments,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct Appended {
80 pub docx: Vec<u8>,
82 pub warnings: Vec<String>,
84}
85
86#[derive(Clone, Debug, PartialEq, Eq)]
88pub enum AppendError {
89 Admission {
91 document: &'static str,
93 error: AdmissionError,
95 },
96 Package {
98 document: &'static str,
100 message: String,
102 },
103 Invalid {
105 document: &'static str,
107 message: String,
109 },
110}
111
112impl AppendError {
113 pub fn code(&self) -> &'static str {
116 match self {
117 Self::Admission { error, .. } => error.code(),
118 Self::Package { .. } => "INVALID_PACKAGE",
119 Self::Invalid { .. } => "INVALID_DOCUMENT",
120 }
121 }
122}
123
124impl fmt::Display for AppendError {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 Self::Admission { document, error } => write!(f, "document {document}: {error}"),
128 Self::Package { document, message } | Self::Invalid { document, message } => {
129 write!(f, "{}: document {document}: {message}", self.code())
130 }
131 }
132 }
133}
134
135impl std::error::Error for AppendError {}
136
137pub fn append_documents(
153 a: &[u8],
154 b: &[u8],
155 options: &AppendOptions,
156) -> Result<Appended, AppendError> {
157 let mut dest = open("A", a)?;
158 let src = open("B", b)?;
159 let parts_before: HashSet<String> = dest.parts().into_iter().collect();
161 let a_main = main_part("A", &dest)?;
162 let b_main = main_part("B", &src)?;
163 let mut dom = Dom::new();
164 let (a_doc, a_root) = parse("A", &mut dom, &dest, &a_main)?;
165 let (_, b_root) = parse("B", &mut dom, &src, &b_main)?;
166 let a_body = body("A", &dom, a_root)?;
167 let b_body = body("B", &dom, b_root)?;
168 let a_sect = final_sect_pr(&dom, a_body);
169 let b_sect = final_sect_pr(&dom, b_body);
170 merge_namespace_declarations(&mut dom, a_root, b_root);
171
172 let staged = dom.new_element(W::body());
175 for child in dom.elements(b_body, None) {
176 if Some(child) != b_sect {
177 let copy = dom.clone_subtree(child);
178 dom.add(staged, copy);
179 }
180 }
181 let b_final_sect = (options.keep_sections)
182 .then_some(b_sect)
183 .flatten()
184 .map(|sect| dom.clone_subtree(sect));
185
186 let carry = options.comments == AppendComments::Carry;
187 let mut warnings = Vec::new();
188 let mut comments = 0;
189 if !carry {
190 comments += drop_comments(&mut dom, staged);
191 }
192 if let Some(sect) = b_final_sect {
193 comments += drop_comments(&mut dom, sect);
194 }
195 offset_annotation_ids(&mut dom, a_root, staged);
196 if let Some(sect) = b_final_sect {
197 offset_annotation_ids(&mut dom, a_root, sect);
199 }
200 drop_colliding_paragraph_ids(&mut dom, a_root, staged);
201
202 let mut notes = Vec::new();
203 for kind in &NOTE_KINDS {
204 if let Some(carried) =
205 carry_notes(kind, &mut dest, &a_main, &src, &b_main, &mut dom, staged)?
206 {
207 comments += drop_comments(&mut dom, carried.staged);
208 notes.push(carried);
209 }
210 }
211
212 let mut roots = vec![staged];
213 roots.extend(notes.iter().map(|n| n.staged));
214 let mut a_comments = None;
215 let mut b_comments = None;
216 if carry {
217 let family = CommentFamily::load(&dest, &a_main).map_err(|e| invalid("A", e))?;
218 let (staged_comments, dropped) =
219 stage_comments(&src, &b_main, &mut dom, &family, a_root, staged)?;
220 comments += dropped;
221 a_comments = Some(family);
222 b_comments = staged_comments;
223 }
224 if let Some(carried) = &b_comments {
225 roots.push(carried.container);
226 }
227 carry_styles_and_numbering(&mut dest, &a_main, &src, &b_main, &mut dom, &roots)?;
228
229 carry_part_relationships(&mut dest, &a_main, &src, &b_main, &mut dom, staged);
230 if let Some(sect) = b_final_sect {
231 carry_part_relationships(&mut dest, &a_main, &src, &b_main, &mut dom, sect);
232 }
233 for note in ¬es {
234 carry_part_relationships(
235 &mut dest,
236 ¬e.dest_part,
237 &src,
238 ¬e.src_part,
239 &mut dom,
240 note.staged,
241 );
242 for child in dom.elements(note.staged, None) {
243 dom.add(note.dest_root, child);
244 }
245 dest.set_part(
246 ¬e.dest_part,
247 dom.serialize_document(note.dest_doc).into_bytes(),
248 );
249 }
250 if let (Some(carried), Some(family)) = (&b_comments, &a_comments) {
251 carry_part_relationships(
252 &mut dest,
253 &family.part_name(),
254 &src,
255 &carried.src_part,
256 &mut dom,
257 carried.container,
258 );
259 }
260 comments += drop_comments_in_new_parts(&mut dest, &parts_before);
261
262 join(&mut dom, a_body, a_sect, staged, b_final_sect, options);
263 dest.set_part(&a_main, dom.serialize_document(a_doc).into_bytes());
264 if let (Some(carried), Some(mut family)) = (b_comments, a_comments) {
265 for comment in dom.elements(carried.container, Some(&W::comment())) {
266 let Some(id) = dom
267 .attribute(comment, &W::id())
268 .and_then(|v| v.parse::<u32>().ok())
269 else {
270 continue;
271 };
272 let (parent, done, date) = carried.state.get(&id).cloned().unwrap_or_default();
273 family.adopt(
274 &dom.serialize_element(comment),
275 id,
276 parent,
277 done,
278 date.as_deref(),
279 );
280 }
281 family.store(&mut dest, &a_main);
282 if let Some(part) = related(&dest, &a_main, "/comments") {
283 merge_part_namespaces(&mut dest, &part, &mut dom, carried.b_root)?;
284 }
285 }
286 if comments > 0 {
287 let (noun, verb) = if comments == 1 {
288 ("comment", "was")
289 } else {
290 ("comments", "were")
291 };
292 warnings.push(format!(
293 "COMMENTS_DROPPED: {comments} {noun} of B {verb} not carried"
294 ));
295 }
296 let bytes = dest.to_zip().map_err(|e| package("output", &e))?;
297 let docx = crate::comparer::fixups::fix_up_drawing_ids_in_package(&bytes)
298 .map_err(|e| package("output", &e))?;
299 Ok(Appended { docx, warnings })
300}
301
302fn package(document: &'static str, error: &OpcError) -> AppendError {
303 AppendError::Package {
304 document,
305 message: error.to_string(),
306 }
307}
308
309fn invalid(document: &'static str, message: impl Into<String>) -> AppendError {
310 AppendError::Invalid {
311 document,
312 message: message.into(),
313 }
314}
315
316#[doc(hidden)]
317pub fn open(document: &'static str, bytes: &[u8]) -> Result<PartFs, AppendError> {
318 crate::admission::admit(bytes, InputLimits::default())
319 .map_err(|error| AppendError::Admission { document, error })?;
320 let normalized =
321 crate::strict_translation::strict_to_transitional_docx(bytes).map_err(|e| {
322 AppendError::Package {
323 document,
324 message: e.to_string(),
325 }
326 })?;
327 PartFs::open(&normalized).map_err(|e| package(document, &e))
328}
329
330fn main_part(document: &'static str, pkg: &PartFs) -> Result<String, AppendError> {
331 pkg.main_document_part()
332 .filter(|part| pkg.part_bytes(part).is_some())
333 .ok_or_else(|| invalid(document, "no main document part"))
334}
335
336fn parse(
338 document: &'static str,
339 dom: &mut Dom,
340 pkg: &PartFs,
341 part: &str,
342) -> Result<(NodeId, NodeId), AppendError> {
343 let xml = pkg
344 .part_bytes(part)
345 .ok_or_else(|| invalid(document, format!("missing part {part}")))?;
346 let xml = std::str::from_utf8(xml).map_err(|e| invalid(document, format!("{part}: {e}")))?;
347 crate::xmllinq::parse::validate_xml(xml)
348 .map_err(|e| invalid(document, format!("{part}: {e}")))?;
349 let doc = dom.parse_xdocument(xml);
350 let root = dom
351 .root(doc)
352 .ok_or_else(|| invalid(document, format!("{part}: missing XML root")))?;
353 Ok((doc, root))
354}
355
356fn body(document: &'static str, dom: &Dom, root: NodeId) -> Result<NodeId, AppendError> {
357 dom.element(root, &W::body())
358 .ok_or_else(|| invalid(document, "the main part has no w:body"))
359}
360
361fn final_sect_pr(dom: &Dom, body: NodeId) -> Option<NodeId> {
362 dom.elements(body, None)
363 .last()
364 .copied()
365 .filter(|&last| dom.name_is(last, &W::sect_pr()))
366}
367
368fn merge_namespace_declarations(dom: &mut Dom, to: NodeId, from: NodeId) {
373 let declared: HashSet<XName> = dom
374 .attributes(to)
375 .into_iter()
376 .filter(|(name, _)| dom.is_namespace_declaration(name))
377 .map(|(name, _)| name)
378 .collect();
379 for (name, uri) in dom.attributes(from) {
380 if dom.is_namespace_declaration(&name) && !declared.contains(&name) {
381 dom.set_attribute_value(to, &name, Some(&uri));
382 }
383 }
384 let ignorable = MC::name("Ignorable");
385 let Some(theirs) = dom.attribute(from, &ignorable).map(str::to_string) else {
386 return;
387 };
388 let mut ours: Vec<String> = dom
389 .attribute(to, &ignorable)
390 .unwrap_or("")
391 .split_whitespace()
392 .map(str::to_string)
393 .collect();
394 for prefix in theirs.split_whitespace() {
395 let declaration = XName::get(prefix, XMLNS);
397 let same = dom
398 .attribute(to, &declaration)
399 .is_some_and(|uri| dom.attribute(from, &declaration) == Some(uri));
400 if same && !ours.iter().any(|p| p == prefix) {
401 ours.push(prefix.to_string());
402 }
403 }
404 if !ours.is_empty() {
405 dom.set_attribute_value(to, &ignorable, Some(&ours.join(" ")));
406 }
407}
408
409fn drop_comments(dom: &mut Dom, root: NodeId) -> usize {
413 drop_comments_where(dom, root, |_| true)
414}
415
416fn comment_anchors(dom: &Dom, root: NodeId) -> Vec<NodeId> {
418 dom.descendants(root, None)
419 .into_iter()
420 .filter(|&el| dom.name(el).is_some_and(|name| is_comment_anchor(&name)))
421 .collect()
422}
423
424fn is_comment_anchor(name: &XName) -> bool {
425 name.namespace_name() == W::URI
426 && matches!(
427 name.local_name(),
428 "commentRangeStart" | "commentRangeEnd" | "commentReference"
429 )
430}
431
432fn drop_comments_where(dom: &mut Dom, root: NodeId, drop: impl Fn(&str) -> bool) -> usize {
434 let mut ids = HashSet::new();
435 for el in comment_anchors(dom, root) {
436 let id = dom.attribute(el, &W::id()).unwrap_or("").to_string();
437 if !drop(&id) {
438 continue;
439 }
440 ids.insert(id);
441 let parent = dom.parent(el);
442 dom.remove(el);
443 if let Some(run) = parent.filter(|&p| dom.name_is(p, &W::r()))
444 && dom
445 .elements(run, None)
446 .iter()
447 .all(|&child| dom.name_is(child, &W::r_pr()))
448 {
449 dom.remove(run);
450 }
451 }
452 ids.len()
453}
454
455fn drop_comments_in_new_parts(dest: &mut PartFs, before: &HashSet<String>) -> usize {
458 let mut dropped = 0;
459 for part in dest.parts() {
460 if before.contains(&part) || !part.ends_with(".xml") {
461 continue;
462 }
463 let Some(xml) = dest.part_string(&part) else {
464 continue;
465 };
466 if !xml.contains("commentR") {
467 continue;
468 }
469 let mut dom = Dom::new();
470 let doc = dom.parse_xdocument(&xml);
471 if let Some(root) = dom.root(doc) {
472 let n = drop_comments(&mut dom, root);
473 if n > 0 {
474 dropped += n;
475 dest.set_part(&part, dom.serialize_document(doc).into_bytes());
476 }
477 }
478 }
479 dropped
480}
481
482const NOT_ANNOTATIONS: &[&str] = &[
486 "footnoteReference",
487 "endnoteReference",
488 "footnote",
489 "endnote",
490 "commentRangeStart",
491 "commentRangeEnd",
492 "commentReference",
493];
494
495fn is_annotation(name: &XName) -> bool {
496 name.namespace_name() == W::URI && !NOT_ANNOTATIONS.contains(&name.local_name())
497}
498
499fn offset_annotation_ids(dom: &mut Dom, existing: NodeId, staged: NodeId) {
503 let highest = dom
504 .descendants(existing, None)
505 .into_iter()
506 .filter(|&el| dom.name(el).is_some_and(|n| is_annotation(&n)))
507 .filter_map(|el| dom.attribute(el, &W::id())?.parse::<i64>().ok())
508 .max()
509 .unwrap_or(-1);
510 let offset = highest.max(-1) + 1;
511 if offset == 0 {
512 return;
513 }
514 for el in dom.descendants(staged, None) {
515 if !dom.name(el).is_some_and(|n| is_annotation(&n)) {
516 continue;
517 }
518 if let Some(id) = dom
519 .attribute(el, &W::id())
520 .and_then(|id| id.parse::<i64>().ok())
521 .filter(|&id| id >= 0)
522 {
523 dom.set_attribute_value(el, &W::id(), Some(&(id + offset).to_string()));
524 }
525 }
526}
527
528fn drop_colliding_paragraph_ids(dom: &mut Dom, existing: NodeId, staged: NodeId) {
531 let para_id = W14::name("paraId");
532 let used: HashSet<String> = dom
533 .descendants(existing, Some(&W::p()))
534 .into_iter()
535 .filter_map(|p| dom.attribute(p, ¶_id).map(str::to_string))
536 .collect();
537 for p in dom.descendants(staged, Some(&W::p())) {
538 if dom
539 .attribute(p, ¶_id)
540 .is_some_and(|id| used.contains(id))
541 {
542 dom.set_attribute_value(p, ¶_id, None);
543 dom.set_attribute_value(p, &W14::name("textId"), None);
544 }
545 }
546}
547
548struct StagedComments {
550 container: NodeId,
552 src_part: String,
554 b_root: NodeId,
556 state: HashMap<u32, (Option<u32>, bool, Option<String>)>,
558}
559
560fn stage_comments(
565 src: &PartFs,
566 b_main: &str,
567 dom: &mut Dom,
568 family: &CommentFamily,
569 a_root: NodeId,
570 staged: NodeId,
571) -> Result<(Option<StagedComments>, usize), AppendError> {
572 let b_family = CommentFamily::load(src, b_main).map_err(|e| invalid("B", e))?;
573 let defined = |id: &str| id.parse::<u32>().is_ok_and(|id| b_family.contains(id));
574 let dropped = drop_comments_where(dom, staged, |id| !defined(id));
575 let anchors = comment_anchors(dom, staged);
576 let anchored: HashSet<u32> = anchors
577 .iter()
578 .filter_map(|&el| dom.attribute(el, &W::id())?.parse().ok())
579 .collect();
580 if anchored.is_empty() {
581 return Ok((None, dropped));
582 }
583 let highest = comment_anchors(dom, a_root)
584 .into_iter()
585 .filter_map(|el| dom.attribute(el, &W::id())?.parse::<u32>().ok())
586 .chain(family.order())
587 .max();
588 let mut next = highest.map_or(0, |h| h + 1);
589 let mut map: HashMap<u32, u32> = HashMap::new();
590 for id in b_family.order() {
591 if anchored.contains(&id) {
592 map.insert(id, next);
593 next += 1;
594 }
595 }
596 for el in anchors {
597 let new = dom
598 .attribute(el, &W::id())
599 .and_then(|v| v.parse::<u32>().ok())
600 .and_then(|id| map.get(&id));
601 if let Some(new) = new {
602 dom.set_attribute_value(el, &W::id(), Some(&new.to_string()));
603 }
604 }
605 let src_part =
606 related(src, b_main, "/comments").ok_or_else(|| invalid("B", "no comments part"))?;
607 let (_, b_root) = parse("B", dom, src, &src_part)?;
608 let container = dom.new_element(W::name("comments"));
609 for comment in dom.elements(b_root, Some(&W::comment())) {
610 let Some(&new) = dom
611 .attribute(comment, &W::id())
612 .and_then(|v| v.parse::<u32>().ok())
613 .and_then(|id| map.get(&id))
614 else {
615 continue;
616 };
617 let copy = dom.clone_subtree(comment);
618 dom.set_attribute_value(copy, &W::id(), Some(&new.to_string()));
619 dom.add(container, copy);
620 }
621 let state = map
622 .iter()
623 .filter_map(|(&old, &new)| {
624 let (parent, done, date) = b_family.thread_state(old)?;
625 Some((new, (parent.and_then(|p| map.get(&p).copied()), done, date)))
626 })
627 .collect();
628 Ok((
629 Some(StagedComments {
630 container,
631 src_part,
632 b_root,
633 state,
634 }),
635 dropped,
636 ))
637}
638
639struct NoteKind {
641 element: &'static str,
642 file: &'static str,
643 rel: &'static str,
644 content_type: &'static str,
645}
646
647const NOTE_KINDS: [NoteKind; 2] = [
648 NoteKind {
649 element: "footnote",
650 file: "footnotes.xml",
651 rel: "/footnotes",
652 content_type: "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
653 },
654 NoteKind {
655 element: "endnote",
656 file: "endnotes.xml",
657 rel: "/endnotes",
658 content_type: "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml",
659 },
660];
661
662struct CarriedNotes {
664 dest_part: String,
665 dest_doc: NodeId,
666 dest_root: NodeId,
667 src_part: String,
668 staged: NodeId,
669}
670
671fn carry_notes(
675 kind: &NoteKind,
676 dest: &mut PartFs,
677 a_main: &str,
678 src: &PartFs,
679 b_main: &str,
680 dom: &mut Dom,
681 staged: NodeId,
682) -> Result<Option<CarriedNotes>, AppendError> {
683 let reference = W::name(&format!("{}Reference", kind.element));
684 let refs = dom.descendants(staged, Some(&reference));
685 if refs.is_empty() {
686 return Ok(None);
687 }
688 let note_name = W::name(kind.element);
689 let src_notes = match related(src, b_main, kind.rel) {
690 Some(part) => Some((parse("B", dom, src, &part)?.1, part)),
691 None => None,
692 };
693 let Some((src_root, src_part)) = src_notes else {
694 for r in refs {
695 dom.remove(r);
696 }
697 return Ok(None);
698 };
699 let dest_part = match related(dest, a_main, kind.rel) {
700 Some(part) => part,
701 None => {
702 let part = free_sibling(dest, a_main, kind.file);
703 let element = kind.element;
704 let xml = format!(
705 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
706 <w:{element}s xmlns:w=\"{w}\" xmlns:r=\"{RELS}\">\
707 <w:{element} w:type=\"separator\" w:id=\"-1\"><w:p><w:pPr>\
708 <w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>\
709 <w:r><w:separator/></w:r></w:p></w:{element}>\
710 <w:{element} w:type=\"continuationSeparator\" w:id=\"0\"><w:p><w:pPr>\
711 <w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>\
712 <w:r><w:continuationSeparator/></w:r></w:p></w:{element}></w:{element}s>",
713 w = W::URI
714 );
715 add_related_part(dest, a_main, &part, kind.rel, kind.content_type, xml);
716 part
717 }
718 };
719 let (dest_doc, dest_root) = parse("A", dom, dest, &dest_part)?;
720 merge_namespace_declarations(dom, dest_root, src_root);
721 let mut next = dom
722 .elements(dest_root, Some(¬e_name))
723 .into_iter()
724 .filter_map(|n| dom.attribute(n, &W::id())?.parse::<i64>().ok())
725 .max()
726 .unwrap_or(0)
727 .max(0)
728 + 1;
729 let by_id: HashMap<String, NodeId> = dom
730 .elements(src_root, Some(¬e_name))
731 .into_iter()
732 .filter_map(|n| Some((dom.attribute(n, &W::id())?.to_string(), n)))
733 .collect();
734 let notes_staged = dom.new_element(W::name(&format!("{}s", kind.element)));
735 let mut renumbered: HashMap<String, String> = HashMap::new();
736 for r in refs {
737 let old = dom.attribute(r, &W::id()).unwrap_or("").to_string();
738 let new = match renumbered.get(&old) {
739 Some(new) => Some(new.clone()),
740 None => by_id.get(&old).map(|¬e| {
741 let copy = dom.clone_subtree(note);
742 let id = next.to_string();
743 next += 1;
744 dom.set_attribute_value(copy, &W::id(), Some(&id));
745 dom.add(notes_staged, copy);
746 renumbered.insert(old.clone(), id.clone());
747 id
748 }),
749 };
750 match new {
751 Some(id) => dom.set_attribute_value(r, &W::id(), Some(&id)),
752 None => dom.remove(r),
753 }
754 }
755 offset_annotation_ids(dom, dest_root, notes_staged);
756 Ok(Some(CarriedNotes {
757 dest_part,
758 dest_doc,
759 dest_root,
760 src_part,
761 staged: notes_staged,
762 }))
763}
764
765#[doc(hidden)]
768pub fn related(pkg: &PartFs, main: &str, kind: &str) -> Option<String> {
769 let rel = pkg
770 .read_rels_for(main)?
771 .items
772 .iter()
773 .find(|r| r.rel_type.ends_with(kind) && r.target_mode.as_deref() != Some("External"))?;
774 let part = pkg.resolve_rel_target(main, &rel.target);
775 pkg.part_bytes(&part).is_some().then_some(part)
776}
777
778fn free_sibling(pkg: &PartFs, main: &str, name: &str) -> String {
780 let dir = main.rsplit_once('/').map_or("", |(dir, _)| dir);
781 let path = |file: &str| {
782 if dir.is_empty() {
783 file.to_string()
784 } else {
785 format!("{dir}/{file}")
786 }
787 };
788 let (stem, ext) = name.rsplit_once('.').unwrap_or((name, "xml"));
789 let mut candidate = path(name);
790 let mut n = 2;
791 while pkg.part_bytes(&candidate).is_some() {
792 candidate = path(&format!("{stem}{n}.{ext}"));
793 n += 1;
794 }
795 candidate
796}
797
798fn add_related_part(
799 pkg: &mut PartFs,
800 main: &str,
801 part: &str,
802 rel: &str,
803 content_type: &str,
804 xml: String,
805) {
806 pkg.add_document_relationship(
807 main,
808 &format!("{RELS}{rel}"),
809 &relative_rel_target(main, part),
810 );
811 pkg.add_content_type_override(&format!("/{part}"), content_type);
812 pkg.set_part(part, xml.into_bytes());
813}
814
815const STYLE_REFERENCES: &[&str] = &["pStyle", "rStyle", "tblStyle", "numStyleLink", "styleLink"];
817const STYLE_CHAIN: &[&str] = &["basedOn", "link", "next"];
819
820fn w_vals(dom: &Dom, root: NodeId, locals: &[&str]) -> Vec<(NodeId, String)> {
821 dom.descendants_and_self(root, None)
822 .into_iter()
823 .filter(|&el| {
824 dom.name(el)
825 .is_some_and(|n| n.namespace_name() == W::URI && locals.contains(&n.local_name()))
826 })
827 .filter_map(|el| Some((el, dom.attribute(el, &W::val())?.to_string())))
828 .collect()
829}
830
831fn style_key(dom: &Dom, style: NodeId) -> Option<(String, String)> {
834 let ty = dom
835 .attribute(style, &W::type_())
836 .unwrap_or("paragraph")
837 .to_string();
838 let name = dom
839 .element(style, &W::name("name"))
840 .and_then(|n| dom.attribute(n, &W::val()))
841 .or_else(|| dom.attribute(style, &W::name("styleId")))?;
842 let key = if crate::builtin_styles::is_built_in(name) {
843 name.to_ascii_lowercase()
844 } else {
845 name.to_string()
846 };
847 Some((ty, key))
848}
849
850fn index_by_attribute(
851 dom: &Dom,
852 root: Option<NodeId>,
853 element: &str,
854 attribute: &str,
855) -> HashMap<String, NodeId> {
856 root.map(|root| {
857 dom.elements(root, Some(&W::name(element)))
858 .into_iter()
859 .filter_map(|el| Some((dom.attribute(el, &W::name(attribute))?.to_string(), el)))
860 .collect()
861 })
862 .unwrap_or_default()
863}
864
865fn carry_styles_and_numbering(
870 dest: &mut PartFs,
871 a_main: &str,
872 src: &PartFs,
873 b_main: &str,
874 dom: &mut Dom,
875 roots: &[NodeId],
876) -> Result<(), AppendError> {
877 let b_styles = related(src, b_main, "/styles")
878 .map(|part| parse("B", dom, src, &part))
879 .transpose()?
880 .map(|(_, root)| root);
881 let b_numbering = related(src, b_main, "/numbering")
882 .map(|part| parse("B", dom, src, &part))
883 .transpose()?
884 .map(|(_, root)| root);
885 let a_styles_part = related(dest, a_main, "/styles");
886 let a_styles = a_styles_part
887 .as_deref()
888 .map(|part| parse("A", dom, dest, part))
889 .transpose()?;
890 let b_by_id = index_by_attribute(dom, b_styles, "style", "styleId");
891 let a_by_id = index_by_attribute(dom, a_styles.map(|(_, root)| root), "style", "styleId");
892 let a_by_key: HashMap<(String, String), String> = a_by_id
893 .iter()
894 .filter_map(|(id, &style)| Some((style_key(dom, style)?, id.clone())))
895 .collect();
896 let b_nums = index_by_attribute(dom, b_numbering, "num", "numId");
897 let b_abstracts = index_by_attribute(dom, b_numbering, "abstractNum", "abstractNumId");
898
899 let mut style_map: HashMap<String, String> = HashMap::new();
902 let mut copied_styles: Vec<String> = Vec::new();
903 let mut nums: Vec<String> = Vec::new();
904 let mut style_queue: Vec<String> = Vec::new();
905 for &root in roots {
906 style_queue.extend(
907 w_vals(dom, root, STYLE_REFERENCES)
908 .into_iter()
909 .map(|(_, v)| v),
910 );
911 }
912 let mut num_queue: Vec<String> = Vec::new();
913 for &root in roots {
914 num_queue.extend(w_vals(dom, root, &["numId"]).into_iter().map(|(_, v)| v));
915 }
916 let mut taken: HashSet<String> = a_by_id.keys().cloned().collect();
917 loop {
918 if let Some(id) = style_queue.pop() {
919 if style_map.contains_key(&id) {
920 continue;
921 }
922 let Some(&style) = b_by_id.get(&id) else {
923 style_map.insert(id.clone(), id);
924 continue;
925 };
926 if let Some(a_id) = style_key(dom, style).and_then(|key| a_by_key.get(&key)) {
927 style_map.insert(id, a_id.clone());
928 continue;
929 }
930 let mut new_id = id.clone();
931 let mut n = 1;
932 while taken.contains(&new_id) {
933 new_id = if n == 1 {
934 format!("{id}B")
935 } else {
936 format!("{id}B{n}")
937 };
938 n += 1;
939 }
940 taken.insert(new_id.clone());
941 style_map.insert(id.clone(), new_id);
942 copied_styles.push(id);
943 style_queue.extend(w_vals(dom, style, STYLE_CHAIN).into_iter().map(|(_, v)| v));
944 num_queue.extend(w_vals(dom, style, &["numId"]).into_iter().map(|(_, v)| v));
945 continue;
946 }
947 if let Some(num_id) = num_queue.pop() {
948 if num_id == "0" || nums.contains(&num_id) {
949 continue;
950 }
951 let Some(&num) = b_nums.get(&num_id) else {
952 continue;
953 };
954 nums.push(num_id);
955 if let Some(abstract_num) = abstract_of(dom, num).and_then(|a| b_abstracts.get(&a)) {
956 style_queue.extend(
957 w_vals(dom, *abstract_num, &["pStyle", "numStyleLink", "styleLink"])
958 .into_iter()
959 .map(|(_, v)| v),
960 );
961 }
962 continue;
963 }
964 break;
965 }
966
967 let mut copies = Vec::new();
969 let mut sheet = None;
970 if !copied_styles.is_empty() {
971 let (styles_doc, styles_root, styles_part) = match (a_styles, a_styles_part) {
972 (Some((doc, root)), Some(part)) => (doc, root, part),
973 _ => {
974 let part = free_sibling(dest, a_main, "styles.xml");
975 add_related_part(
976 dest,
977 a_main,
978 &part,
979 "/styles",
980 "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
981 format!(
982 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
983 <w:styles xmlns:w=\"{}\"></w:styles>",
984 W::URI
985 ),
986 );
987 let (doc, root) = parse("A", dom, dest, &part)?;
988 (doc, root, part)
989 }
990 };
991 if let Some(b_root) = b_styles {
992 merge_namespace_declarations(dom, styles_root, b_root);
993 }
994 for id in &copied_styles {
995 let copy = dom.clone_subtree(b_by_id[id]);
996 dom.set_attribute_value(copy, &W::name("styleId"), Some(&style_map[id]));
997 dom.set_attribute_value(copy, &W::name("default"), None);
999 for (el, val) in w_vals(dom, copy, STYLE_CHAIN) {
1000 if let Some(new) = style_map.get(&val) {
1001 dom.set_attribute_value(el, &W::val(), Some(new));
1002 }
1003 }
1004 dom.add(styles_root, copy);
1005 copies.push(copy);
1006 }
1007 sheet = Some((styles_doc, styles_part));
1009 }
1010
1011 for &root in roots {
1012 for (el, val) in w_vals(dom, root, &["pStyle", "rStyle", "tblStyle"]) {
1013 if let Some(new) = style_map.get(&val).filter(|new| **new != val) {
1014 dom.set_attribute_value(el, &W::val(), Some(new));
1015 }
1016 }
1017 }
1018
1019 let mut num_map: HashMap<String, String> = HashMap::new();
1021 if !nums.is_empty() {
1022 let used_nsids = related(dest, a_main, "/numbering")
1023 .and_then(|part| dest.part_string(&part))
1024 .map(|xml| nsids(&xml))
1025 .unwrap_or_default();
1026 let mut abstracts: Vec<String> = Vec::new();
1027 for num_id in &nums {
1028 if let Some(a) = abstract_of(dom, b_nums[num_id])
1029 && b_abstracts.contains_key(&a)
1030 && !abstracts.contains(&a)
1031 {
1032 abstracts.push(a);
1033 }
1034 }
1035 let lists = ListCopy {
1036 b_abstracts: &b_abstracts,
1037 b_nums: &b_nums,
1038 style_map: &style_map,
1039 abstracts: &abstracts,
1040 nums: &nums,
1041 used_nsids: &used_nsids,
1042 };
1043 let part_before = related(dest, a_main, "/numbering")
1044 .and_then(|part| dest.part_bytes(&part).map(<[u8]>::to_vec));
1045 let mut built = None;
1046 let spliced =
1047 crate::numbering::append_numbering(dest, a_main, |first_abstract, first_num| {
1048 let (abstracts_xml, nums_xml, map) = lists.build(dom, first_abstract, first_num);
1049 built = Some(map);
1050 (abstracts_xml, nums_xml)
1051 });
1052 let part = related(dest, a_main, "/numbering");
1053 let part_after = part.as_deref().and_then(|part| dest.part_bytes(part));
1054 num_map = if spliced.is_some() && part_after != part_before.as_deref() {
1055 built.unwrap_or_default()
1056 } else {
1057 part.and_then(|part| insert_lists(dest, &part, dom, &lists))
1060 .unwrap_or_default()
1061 };
1062 if let (Some(b_root), Some(part)) = (b_numbering, related(dest, a_main, "/numbering")) {
1065 merge_part_namespaces(dest, &part, dom, b_root)?;
1066 }
1067 }
1068 let mut numbered_roots = roots.to_vec();
1069 numbered_roots.extend(copies.iter().copied());
1070 for root in numbered_roots {
1071 for (el, val) in w_vals(dom, root, &["numId"]) {
1072 if let Some(new) = num_map.get(&val) {
1073 dom.set_attribute_value(el, &W::val(), Some(new));
1074 }
1075 }
1076 }
1077 if let Some((doc, part)) = sheet {
1078 dest.set_part(&part, dom.serialize_document(doc).into_bytes());
1079 }
1080 Ok(())
1081}
1082
1083fn merge_part_namespaces(
1087 dest: &mut PartFs,
1088 part: &str,
1089 dom: &mut Dom,
1090 from: NodeId,
1091) -> Result<(), AppendError> {
1092 let (doc, root) = parse("output", dom, dest, part)?;
1093 let before = dom.attributes(root);
1094 merge_namespace_declarations(dom, root, from);
1095 if dom.attributes(root) != before {
1096 dest.set_part(part, dom.serialize_document(doc).into_bytes());
1097 }
1098 Ok(())
1099}
1100
1101struct ListCopy<'a> {
1103 b_abstracts: &'a HashMap<String, NodeId>,
1104 b_nums: &'a HashMap<String, NodeId>,
1105 style_map: &'a HashMap<String, String>,
1106 abstracts: &'a [String],
1108 nums: &'a [String],
1110 used_nsids: &'a HashSet<String>,
1111}
1112
1113impl ListCopy<'_> {
1114 fn build(
1117 &self,
1118 dom: &mut Dom,
1119 first_abstract: u32,
1120 first_num: u32,
1121 ) -> (String, String, HashMap<String, String>) {
1122 let mut abstract_map = HashMap::new();
1123 let mut used = self.used_nsids.clone();
1124 let mut abstracts_xml = String::new();
1125 for (k, old) in self.abstracts.iter().enumerate() {
1126 let new = first_abstract + u32::try_from(k).unwrap_or(0);
1127 abstract_map.insert(old.clone(), new.to_string());
1128 let copy = dom.clone_subtree(self.b_abstracts[old]);
1129 dom.set_attribute_value(copy, &W::name("abstractNumId"), Some(&new.to_string()));
1130 unique_nsid(dom, copy, &mut used);
1131 for pic in dom.descendants(copy, Some(&W::name("lvlPicBulletId"))) {
1133 dom.remove(pic);
1134 }
1135 for (el, val) in w_vals(dom, copy, &["pStyle", "numStyleLink", "styleLink"]) {
1136 if let Some(new) = self.style_map.get(&val) {
1137 dom.set_attribute_value(el, &W::val(), Some(new));
1138 }
1139 }
1140 abstracts_xml.push_str(&dom.serialize_element(copy));
1141 }
1142 let mut num_map = HashMap::new();
1143 let mut nums_xml = String::new();
1144 for (k, old) in self.nums.iter().enumerate() {
1145 let new = first_num + u32::try_from(k).unwrap_or(0);
1146 num_map.insert(old.clone(), new.to_string());
1147 let copy = dom.clone_subtree(self.b_nums[old]);
1148 dom.set_attribute_value(copy, &W::name("numId"), Some(&new.to_string()));
1149 for el in dom.elements(copy, Some(&W::name("abstractNumId"))) {
1150 let mapped = dom
1151 .attribute(el, &W::val())
1152 .and_then(|v| abstract_map.get(v))
1153 .cloned();
1154 dom.set_attribute_value(el, &W::val(), mapped.as_deref());
1155 }
1156 nums_xml.push_str(&dom.serialize_element(copy));
1157 }
1158 (abstracts_xml, nums_xml, num_map)
1159 }
1160}
1161
1162fn insert_lists(
1165 dest: &mut PartFs,
1166 part: &str,
1167 dom: &mut Dom,
1168 lists: &ListCopy<'_>,
1169) -> Option<HashMap<String, String>> {
1170 let xml = dest.part_string(part)?;
1171 let mut sheet = Dom::new();
1172 let doc = sheet.parse_xdocument(&xml);
1173 let root = sheet.root(doc)?;
1174 let next = |sheet: &Dom, element: &str, attribute: &str| {
1175 let highest = sheet
1176 .elements(root, Some(&W::name(element)))
1177 .into_iter()
1178 .filter_map(|el| {
1179 sheet
1180 .attribute(el, &W::name(attribute))?
1181 .parse::<i64>()
1182 .ok()
1183 })
1184 .max()
1185 .unwrap_or(0)
1186 .max(0);
1187 u32::try_from(highest + 1).unwrap_or(1)
1188 };
1189 let first_abstract = next(&sheet, "abstractNum", "abstractNumId");
1190 let first_num = next(&sheet, "num", "numId");
1191 let (abstracts_xml, nums_xml, num_map) = lists.build(dom, first_abstract, first_num);
1192 for fragment in [abstracts_xml, nums_xml] {
1193 let wrapper = sheet.parse_xdocument(&format!("<fragment>{fragment}</fragment>"));
1194 let Some(wrapper) = sheet.root(wrapper) else {
1195 continue;
1196 };
1197 for child in sheet.elements(wrapper, None) {
1198 sheet.remove(child);
1199 add_in_numbering_order(&mut sheet, root, child);
1200 }
1201 }
1202 dest.set_part(part, sheet.serialize_document(doc).into_bytes());
1203 Some(num_map)
1204}
1205
1206fn add_in_numbering_order(dom: &mut Dom, numbering: NodeId, child: NodeId) {
1208 let rank = |dom: &Dom, el: NodeId| match dom.name(el).as_ref().map(XName::local_name) {
1209 Some("numPicBullet") => 0,
1210 Some("abstractNum") => 1,
1211 Some("num") => 2,
1212 _ => 3,
1213 };
1214 let own = rank(dom, child);
1215 let later = dom
1216 .elements(numbering, None)
1217 .into_iter()
1218 .find(|&el| rank(dom, el) > own);
1219 match later {
1220 Some(el) => dom.add_before_self(el, child),
1221 None => dom.add(numbering, child),
1222 }
1223}
1224
1225fn abstract_of(dom: &Dom, num: NodeId) -> Option<String> {
1226 let el = dom.element(num, &W::name("abstractNumId"))?;
1227 dom.attribute(el, &W::val()).map(str::to_string)
1228}
1229
1230fn nsids(xml: &str) -> HashSet<String> {
1232 let mut dom = Dom::new();
1233 let doc = dom.parse_xdocument(xml);
1234 dom.root(doc)
1235 .map(|root| {
1236 dom.descendants(root, Some(&W::name("nsid")))
1237 .into_iter()
1238 .filter_map(|el| dom.attribute(el, &W::val()).map(str::to_ascii_uppercase))
1239 .collect()
1240 })
1241 .unwrap_or_default()
1242}
1243
1244fn unique_nsid(dom: &mut Dom, abstract_num: NodeId, used: &mut HashSet<String>) {
1247 let Some(el) = dom.element(abstract_num, &W::name("nsid")) else {
1248 return;
1249 };
1250 let current = dom
1251 .attribute(el, &W::val())
1252 .unwrap_or("")
1253 .to_ascii_uppercase();
1254 if !used.contains(¤t) {
1255 used.insert(current);
1256 return;
1257 }
1258 let mut value = u32::from_str_radix(¤t, 16).unwrap_or(0);
1259 let mut candidate = current;
1260 while used.contains(&candidate) {
1261 value = value.wrapping_add(1);
1262 candidate = format!("{value:08X}");
1263 }
1264 dom.set_attribute_value(el, &W::val(), Some(&candidate));
1265 used.insert(candidate);
1266}
1267
1268fn join(
1270 dom: &mut Dom,
1271 a_body: NodeId,
1272 a_sect: Option<NodeId>,
1273 staged: NodeId,
1274 b_final_sect: Option<NodeId>,
1275 options: &AppendOptions,
1276) {
1277 let mut joined: Vec<NodeId> = Vec::new();
1278 match b_final_sect {
1279 Some(b_sect) => {
1280 let paragraph = dom.new_element(W::p());
1283 let ppr = dom.new_element(W::p_pr());
1284 let a_props = match a_sect {
1285 Some(sect) => dom.clone_subtree(sect),
1286 None => dom.new_element(W::sect_pr()),
1287 };
1288 dom.add(ppr, a_props);
1289 dom.add(paragraph, ppr);
1290 joined.push(paragraph);
1291 set_section_type(dom, b_sect, options.section_break);
1292 }
1293 None if options.section_break == SectionBreak::NextPage => {
1294 let paragraph = dom.new_element(W::p());
1295 let run = dom.new_element(W::r());
1296 let br = dom.new_element(W::name("br"));
1297 dom.set_attribute_value(br, &W::type_(), Some("page"));
1298 dom.add(run, br);
1299 dom.add(paragraph, run);
1300 joined.push(paragraph);
1301 }
1302 None => {}
1303 }
1304 joined.extend(dom.elements(staged, None));
1305 for node in joined {
1306 dom.remove(node);
1307 match a_sect {
1308 Some(sect) => dom.add_before_self(sect, node),
1309 None => dom.add(a_body, node),
1310 }
1311 }
1312 if let Some(b_sect) = b_final_sect {
1313 match a_sect {
1314 Some(sect) => dom.replace_with(sect, &[b_sect]),
1315 None => dom.add(a_body, b_sect),
1316 }
1317 }
1318}
1319
1320const BEFORE_TYPE: &[&str] = &[
1322 "headerReference",
1323 "footerReference",
1324 "footnotePr",
1325 "endnotePr",
1326];
1327
1328fn set_section_type(dom: &mut Dom, sect: NodeId, section_break: SectionBreak) {
1331 let type_name = W::type_();
1332 for old in dom.elements(sect, Some(&type_name)) {
1333 dom.remove(old);
1334 }
1335 if section_break == SectionBreak::NextPage {
1336 return;
1337 }
1338 let el = dom.new_element(type_name);
1339 dom.set_attribute_value(el, &W::val(), Some("continuous"));
1340 let after = dom.elements(sect, None).into_iter().find(|&child| {
1341 !dom.name(child)
1342 .is_some_and(|n| n.namespace_name() == W::URI && BEFORE_TYPE.contains(&n.local_name()))
1343 });
1344 match after {
1345 Some(child) => dom.add_before_self(child, el),
1346 None => dom.add(sect, el),
1347 }
1348}
1349
1350#[cfg(test)]
1351#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1352mod tests {
1353 use super::*;
1354
1355 #[test]
1356 fn nsid_collisions_take_the_next_free_value() {
1357 let mut dom = Dom::new();
1358 let doc = dom.parse_xdocument(&format!(
1359 r#"<w:abstractNum xmlns:w="{}"><w:nsid w:val="0000000a"/></w:abstractNum>"#,
1360 W::URI
1361 ));
1362 let root = dom.root(doc).unwrap();
1363 let mut used: HashSet<String> = ["0000000A", "0000000B"].map(String::from).into();
1364 unique_nsid(&mut dom, root, &mut used);
1365 let nsid = dom.element(root, &W::name("nsid")).unwrap();
1366 assert_eq!(dom.attribute(nsid, &W::val()), Some("0000000C"));
1367 assert!(used.contains("0000000C"));
1368 }
1369
1370 #[test]
1371 fn free_sibling_numbers_a_taken_name() {
1372 let mut pkg = PartFs::open(&minimal()).unwrap();
1373 assert_eq!(
1374 free_sibling(&pkg, "word/document.xml", "extra.xml"),
1375 "word/extra.xml"
1376 );
1377 pkg.set_part("word/extra.xml", b"<x/>".to_vec());
1378 assert_eq!(
1379 free_sibling(&pkg, "word/document.xml", "extra.xml"),
1380 "word/extra2.xml"
1381 );
1382 assert_eq!(free_sibling(&pkg, "document.xml", "extra.xml"), "extra.xml");
1383 }
1384
1385 #[test]
1386 fn error_codes_and_messages_name_the_document() {
1387 let error = invalid("B", "no body");
1388 assert_eq!(error.code(), "INVALID_DOCUMENT");
1389 assert_eq!(error.to_string(), "INVALID_DOCUMENT: document B: no body");
1390 let error = AppendError::Package {
1391 document: "A",
1392 message: "bad zip".into(),
1393 };
1394 assert_eq!(error.code(), "INVALID_PACKAGE");
1395 let Err(refused) = open("A", b"") else {
1396 panic!("an empty input was admitted");
1397 };
1398 assert!(refused.to_string().starts_with("document A: "), "{refused}");
1399 assert_ne!(refused.code(), "");
1400 }
1401
1402 #[test]
1403 fn section_type_sits_after_header_references() {
1404 let mut dom = Dom::new();
1405 let doc = dom.parse_xdocument(&format!(
1406 r#"<w:sectPr xmlns:w="{}"><w:headerReference/><w:type w:val="oddPage"/><w:pgSz/></w:sectPr>"#,
1407 W::URI
1408 ));
1409 let sect = dom.root(doc).unwrap();
1410 set_section_type(&mut dom, sect, SectionBreak::None);
1411 let names: Vec<String> = dom
1412 .elements(sect, None)
1413 .into_iter()
1414 .map(|e| dom.name(e).unwrap().local_name().to_string())
1415 .collect();
1416 assert_eq!(names, ["headerReference", "type", "pgSz"]);
1417 set_section_type(&mut dom, sect, SectionBreak::NextPage);
1418 assert!(dom.element(sect, &W::type_()).is_none());
1419 }
1420
1421 #[test]
1422 fn ignorable_prefixes_merge_only_with_the_same_namespace() {
1423 let mut dom = Dom::new();
1424 let mc = MC::URI;
1425 let to = dom.parse_xdocument(&format!(
1426 r#"<w:document xmlns:w="{w}" xmlns:mc="{mc}" xmlns:x="urn:a"/>"#,
1427 w = W::URI
1428 ));
1429 let from = dom.parse_xdocument(&format!(
1430 r#"<w:document xmlns:w="{w}" xmlns:mc="{mc}" xmlns:x="urn:b" xmlns:w14="{w14}" mc:Ignorable="x w14"/>"#,
1431 w = W::URI,
1432 w14 = W14::URI
1433 ));
1434 let (to, from) = (dom.root(to).unwrap(), dom.root(from).unwrap());
1435 merge_namespace_declarations(&mut dom, to, from);
1436 assert_eq!(dom.attribute(to, &MC::name("Ignorable")), Some("w14"));
1438 assert_eq!(dom.attribute(to, &XName::get("x", XMLNS)), Some("urn:a"));
1439 assert_eq!(dom.attribute(to, &XName::get("w14", XMLNS)), Some(W14::URI));
1440 }
1441
1442 fn minimal() -> Vec<u8> {
1443 include_bytes!("../../../tests/fixtures/split/minimal.docx").to_vec()
1444 }
1445}
1446
1447#[cfg(test)]
1448#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1449mod public_memory_append_owner_boundary_tests {
1450 use super::*;
1451 fn semantic(dom: &Dom, node: NodeId) -> String {
1452 if !dom.is_element(node) {
1453 return format!("text:{:?}", dom.text_value(node));
1454 }
1455 let mut attrs = dom
1456 .attributes_iter(node)
1457 .filter(|(name, _)| !dom.is_namespace_declaration(name))
1458 .map(|(name, value)| {
1459 (
1460 name.namespace_name().to_owned(),
1461 name.local_name().to_owned(),
1462 value,
1463 )
1464 })
1465 .collect::<Vec<_>>();
1466 attrs.sort();
1467 format!(
1468 "{:?}{attrs:?}[{}]",
1469 dom.name(node),
1470 dom.nodes(node)
1471 .into_iter()
1472 .map(|child| semantic(dom, child))
1473 .collect::<String>()
1474 )
1475 }
1476 fn document(body: &str) -> String {
1477 format!(
1478 "<w:document xmlns:w='{}' xmlns:w14='{}' xmlns:mc='{}' mc:Ignorable='w14'><w:body>{body}</w:body></w:document>",
1479 W::URI,
1480 W14::URI,
1481 crate::namespaces::MC::URI
1482 )
1483 }
1484 fn package(body: &str) -> PartFs {
1485 let mut pkg = PartFs::open(include_bytes!(
1486 "../../../tests/fixtures/redline/original.docx"
1487 ))
1488 .unwrap();
1489 pkg.set_part("word/document.xml", document(body).into_bytes());
1490 pkg.set_part(
1491 "customXml/source-owned.bin",
1492 b"Independent source ownership bytes".to_vec(),
1493 );
1494 pkg.add_content_type_override("/customXml/source-owned.bin", "application/octet-stream");
1495 pkg
1496 }
1497 fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
1498 let mut parts = pkg.parts();
1499 parts.sort();
1500 parts
1501 .into_iter()
1502 .map(|name| {
1503 let bytes = pkg.part_bytes(&name).unwrap().to_vec();
1504 (name, bytes)
1505 })
1506 .collect()
1507 }
1508 fn view(xml: &str) -> String {
1509 let mut dom = Dom::new();
1510 let doc = dom.parse_xdocument(xml);
1511 let root = dom.root(doc).unwrap();
1512 semantic(&dom, dom.element(root, &W::body()).unwrap())
1513 }
1514 #[test]
1515 fn public_append_keeps_source_property_history_and_fresh_annotation_owners_at_every_join_boundary()
1516 {
1517 let a = "<w:p w14:paraId='10000001' w14:textId='20000001'><w:pPr><w:pStyle w:val='Normal'/><w:spacing w:after='120'/></w:pPr><w:bookmarkStart w:id='3' w:name='OriginalBookmark'/><w:r><w:rPr><w:b/><w:color w:val='123456'/></w:rPr><w:t>Original source payload</w:t></w:r><w:bookmarkEnd w:id='3'/></w:p>";
1518 let a_sect = "<w:sectPr><w:pgSz w:w='12240' w:h='15840'/><w:pgMar w:top='720' w:right='900' w:bottom='720' w:left='900'/></w:sectPr>";
1519 let b_sect = "<w:sectPr><w:footnotePr><w:pos w:val='beneathText'/></w:footnotePr><w:pgSz w:w='14400' w:h='18000'/><w:pgMar w:top='900' w:right='720' w:bottom='900' w:left='720'/></w:sectPr>";
1520 for collision in [false, true] {
1521 for keep_sections in [false, true] {
1522 for section_break in [
1523 SectionBreak::NextPage,
1524 SectionBreak::Continuous,
1525 SectionBreak::None,
1526 ] {
1527 let para_id = if collision { "10000001" } else { "10000002" };
1528 let b = format!(
1529 "<w:p w14:paraId='{para_id}' w14:textId='20000002'><w:pPr><w:pStyle w:val='Normal'/><w:spacing w:after='240'/><w:pPrChange w:id='2' w:author='Earlier format owner' w:date='2025-02-03T04:05:06Z'><w:pPr><w:spacing w:after='60'/></w:pPr></w:pPrChange></w:pPr><w:bookmarkStart w:id='0' w:name='RevisedBookmark'/><w:ins w:id='1' w:author='Pending source owner' w:date='2025-03-04T05:06:07Z'><w:r><w:rPr><w:i/><w:color w:val='654321'/></w:rPr><w:t>Revised source payload</w:t></w:r></w:ins><w:bookmarkEnd w:id='0'/></w:p>"
1530 );
1531 let ap = package(&(a.to_string() + a_sect));
1532 let bp = package(&(b.clone() + b_sect));
1533 let a_snapshot = snapshot(&ap);
1534 let b_snapshot = snapshot(&bp);
1535 let a_bytes = ap.to_zip().unwrap();
1536 let b_bytes = bp.to_zip().unwrap();
1537 let options = AppendOptions {
1538 section_break,
1539 keep_sections,
1540 comments: AppendComments::Carry,
1541 };
1542 let out = append_documents(&a_bytes, &b_bytes, &options).unwrap();
1543 assert!(out.warnings.is_empty());
1544 let result = PartFs::open(&out.docx).unwrap();
1545 let mut copied_b = b
1546 .replace("w:id='2'", "w:id='6'")
1547 .replace("w:id='1'", "w:id='5'")
1548 .replace("w:id='0'", "w:id='4'");
1549 if collision {
1550 copied_b = copied_b
1551 .replace(" w14:paraId='10000001'", "")
1552 .replace(" w14:textId='20000002'", "");
1553 }
1554 let join = if keep_sections {
1555 format!("<w:p><w:pPr>{a_sect}</w:pPr></w:p>")
1556 } else if section_break == SectionBreak::NextPage {
1557 "<w:p><w:r><w:br w:type='page'/></w:r></w:p>".into()
1558 } else {
1559 String::new()
1560 };
1561 let final_sect = if keep_sections && section_break != SectionBreak::NextPage {
1562 b_sect.replace(
1563 "</w:footnotePr>",
1564 "</w:footnotePr><w:type w:val='continuous'/>",
1565 )
1566 } else if keep_sections {
1567 b_sect.to_string()
1568 } else {
1569 a_sect.to_string()
1570 };
1571 assert_eq!(
1572 view(&result.part_string("word/document.xml").unwrap()),
1573 view(&document(&format!("{a}{join}{copied_b}{final_sect}"))),
1574 "collision={collision}, keep={keep_sections}, boundary={section_break:?}: all source properties and owner metadata"
1575 );
1576 assert_eq!(
1577 result.part_bytes("customXml/source-owned.bin"),
1578 Some(b"Independent source ownership bytes".as_slice())
1579 );
1580 assert_eq!(
1581 result.part_bytes("word/_rels/document.xml.rels"),
1582 ap.part_bytes("word/_rels/document.xml.rels"),
1583 "no unrelated relationships may be invented or lost"
1584 );
1585 let repeated = append_documents(&a_bytes, &b_bytes, &options).unwrap();
1586 let again = PartFs::open(&repeated.docx).unwrap();
1587 assert_eq!(
1588 view(&again.part_string("word/document.xml").unwrap()),
1589 view(&result.part_string("word/document.xml").unwrap())
1590 );
1591 assert_eq!(snapshot(&PartFs::open(&a_bytes).unwrap()), a_snapshot);
1592 assert_eq!(snapshot(&PartFs::open(&b_bytes).unwrap()), b_snapshot);
1593 }
1594 }
1595 }
1596 }
1597 fn verify_styles_xml(
1598 out: &PartFs,
1599 b_style: &str,
1600 renamed: &str,
1601 a_styles: &str,
1602 base: &str,
1603 run: &str,
1604 ) {
1605 let mut dom = Dom::new();
1606 let doc = dom.parse_xdocument(&out.part_string("word/styles.xml").unwrap());
1607 let root = dom.root(doc).unwrap();
1608 let by_id = |id: &str| {
1609 dom.elements(root, Some(&W::name("style")))
1610 .into_iter()
1611 .find(|&style| dom.attribute(style, &W::name("styleId")) == Some(id))
1612 .unwrap()
1613 };
1614 let expected_style = b_style
1615 .replace(" w:default='1'", "")
1616 .replace("w:styleId='Shared'", &format!("w:styleId='{renamed}'"))
1617 .replace("w:numId w:val='1'", "w:numId w:val='6'");
1618
1619 let styles_root =
1620 |children: &str| format!("<w:styles xmlns:w='{}'>{children}</w:styles>", W::URI);
1621 let mut expected_dom = Dom::new();
1622 let expected_doc = expected_dom.parse_xdocument(&styles_root(&format!(
1623 "{a_styles}{expected_style}{base}{run}"
1624 )));
1625 let expected_root = expected_dom.root(expected_doc).unwrap();
1626 for style in dom.elements(root, Some(&W::name("style"))) {
1627 let id = dom.attribute(style, &W::name("styleId")).unwrap();
1628 let expected = expected_dom
1629 .elements(expected_root, Some(&W::name("style")))
1630 .into_iter()
1631 .find(|&s| expected_dom.attribute(s, &W::name("styleId")) == Some(id))
1632 .unwrap();
1633 assert_eq!(
1634 semantic(&dom, style),
1635 semantic(&expected_dom, expected),
1636 "entire style owner {id}"
1637 );
1638 }
1639 assert_eq!(
1640 dom.elements(root, Some(&W::name("style"))).len(),
1641 expected_dom
1642 .elements(expected_root, Some(&W::name("style")))
1643 .len()
1644 );
1645 assert_eq!(dom.attribute(by_id(renamed), &W::name("default")), None);
1646 assert_eq!(
1647 semantic(&dom, dom.element(root, &W::name("docDefaults")).unwrap()),
1648 semantic(
1649 &expected_dom,
1650 expected_dom
1651 .element(expected_root, &W::name("docDefaults"))
1652 .unwrap()
1653 )
1654 );
1655 }
1656
1657 fn verify_numbering_xml(
1658 out: &PartFs,
1659 disabled_list: bool,
1660 a_numbering: &str,
1661 b_numbering: &str,
1662 nsid: &str,
1663 collision_nsid: bool,
1664 alternate_prefix: bool,
1665 ) {
1666 let canonical_xml = |xml: &str| {
1667 let mut dom = Dom::new();
1668 let doc = dom.parse_xdocument(xml);
1669 semantic(&dom, dom.root(doc).unwrap())
1670 };
1671
1672 let numbering = out.part_string("word/numbering.xml").unwrap();
1673 if disabled_list {
1674 assert_eq!(canonical_xml(&numbering), canonical_xml(a_numbering));
1675 } else {
1676 let copied = b_numbering
1677 .replace("w:abstractNumId='1'", "w:abstractNumId='5'")
1678 .replace("w:numId='1'", "w:numId='6'")
1679 .replace("w:abstractNumId w:val='1'", "w:abstractNumId w:val='5'")
1680 .replace(
1681 &format!("w:val='{nsid}'"),
1682 &format!("w:val='{}'", if collision_nsid { "00000001" } else { nsid }),
1683 );
1684 let copied_inner = copied
1685 .split_once('>')
1686 .unwrap()
1687 .1
1688 .strip_suffix("</w:numbering>")
1689 .unwrap();
1690 let a_abstract_end = a_numbering.find("<w:num ").unwrap();
1691 let a_close = a_numbering.find("</w:numbering>").unwrap();
1692 let copied_num_start = copied_inner.find("<w:num ").unwrap();
1693 let expected = format!(
1694 "{}{}{}{}{}",
1695 &a_numbering[..a_abstract_end],
1696 &copied_inner[..copied_num_start],
1697 &a_numbering[a_abstract_end..a_close],
1698 &copied_inner[copied_num_start..],
1699 "</w:numbering>"
1700 );
1701 assert_eq!(
1702 canonical_xml(&numbering),
1703 canonical_xml(&expected),
1704 "all A/B abstract and concrete properties, prefix={alternate_prefix} collision={collision_nsid}"
1705 );
1706 }
1707 }
1708
1709 fn check_style_collisions_for_permutation(
1710 alternate_prefix: bool,
1711 disabled_list: bool,
1712 second_collision: bool,
1713 collision_nsid: bool,
1714 ) {
1715 let paragraph = |style: &str, text: &str| {
1716 format!(
1717 "<w:p><w:pPr><w:pStyle w:val='{style}'/><w:spacing w:before='120' w:after='80'/></w:pPr><w:r><w:rPr><w:rStyle w:val='RunB'/><w:rFonts w:ascii='Calibri' w:hAnsi='Calibri'/><w:color w:val='123456'/><w:sz w:val='22'/></w:rPr><w:t>{text}</w:t><w:tab/><w:br w:type='column'/></w:r></w:p>"
1718 )
1719 };
1720 let original = "<w:p><w:pPr><w:pStyle w:val='Shared'/><w:ind w:left='180'/></w:pPr><w:r><w:rPr><w:rFonts w:ascii='Arial' w:hAnsi='Arial'/><w:b/></w:rPr><w:t>Original independently owned body</w:t></w:r></w:p>";
1721 let section = "<w:sectPr><w:pgSz w:w='12240' w:h='15840'/><w:pgMar w:top='720' w:right='900' w:bottom='720' w:left='900'/></w:sectPr>";
1722 let base = "<w:style w:type='paragraph' w:styleId='BaseB'><w:name w:val='Revised inherited base'/><w:pPr><w:spacing w:after='240'/></w:pPr><w:rPr><w:i/></w:rPr></w:style>";
1723 let run = "<w:style w:type='character' w:styleId='RunB'><w:name w:val='Revised run owner'/><w:rPr><w:color w:val='654321'/><w:i/></w:rPr></w:style>";
1724 let styles_root =
1725 |children: &str| format!("<w:styles xmlns:w='{}'>{children}</w:styles>", W::URI);
1726
1727 let num_id = if disabled_list { "0" } else { "1" };
1728 let b_style = format!(
1729 "<w:style w:type='paragraph' w:default='1' w:styleId='Shared'><w:name w:val='Revised paragraph owner'/><w:basedOn w:val='BaseB'/><w:next w:val='BaseB'/><w:pPr><w:numPr><w:ilvl w:val='0'/><w:numId w:val='{num_id}'/></w:numPr><w:ind w:left='360'/></w:pPr><w:rPr><w:color w:val='ABCDEF'/></w:rPr></w:style>"
1730 );
1731 let a_styles = format!(
1732 "<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii='Arial' w:hAnsi='Arial'/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type='paragraph' w:default='1' w:styleId='Shared'><w:name w:val='Original paragraph owner'/><w:pPr><w:keepNext/></w:pPr></w:style>{}",
1733 if second_collision {
1734 "<w:style w:type='paragraph' w:styleId='SharedB'><w:name w:val='Independent reserved style id'/><w:rPr><w:u w:val='single'/></w:rPr></w:style>"
1735 } else {
1736 ""
1737 }
1738 );
1739 let a_numbering = format!(
1740 "<w:numbering xmlns:w='{}'><w:abstractNum w:abstractNumId='3'><w:nsid w:val='FFFFFFFF'/><w:multiLevelType w:val='singleLevel'/><w:lvl w:ilvl='0'><w:start w:val='1'/><w:numFmt w:val='decimal'/><w:lvlText w:val='%1.'/></w:lvl></w:abstractNum><w:abstractNum w:abstractNumId='4'><w:nsid w:val='00000000'/><w:multiLevelType w:val='singleLevel'/><w:lvl w:ilvl='0'><w:start w:val='1'/><w:numFmt w:val='lowerLetter'/><w:lvlText w:val='%1.'/></w:lvl></w:abstractNum><w:num w:numId='5'><w:abstractNumId w:val='3'/><w:lvlOverride w:ilvl='0'><w:startOverride w:val='4'/></w:lvlOverride></w:num></w:numbering>",
1741 W::URI
1742 );
1743 let nsid = if collision_nsid {
1744 "FFFFFFFF"
1745 } else {
1746 "12345678"
1747 };
1748 let b_numbering = format!(
1749 "<w:numbering xmlns:w='{}'><w:abstractNum w:abstractNumId='1'><w:nsid w:val='{nsid}'/><w:multiLevelType w:val='singleLevel'/><w:lvl w:ilvl='0'><w:start w:val='3'/><w:numFmt w:val='upperRoman'/><w:pStyle w:val='BaseB'/><w:lvlText w:val='%1.'/><w:lvlJc w:val='right'/><w:pPr><w:tabs><w:tab w:val='num' w:pos='720'/></w:tabs><w:ind w:left='720' w:hanging='360'/></w:pPr><w:rPr><w:rFonts w:ascii='Calibri' w:hAnsi='Calibri'/></w:rPr></w:lvl></w:abstractNum><w:num w:numId='1'><w:abstractNumId w:val='1'/><w:lvlOverride w:ilvl='0'><w:startOverride w:val='7'/></w:lvlOverride></w:num></w:numbering>",
1750 W::URI
1751 );
1752 let mut a = package(&format!("{original}{section}"));
1753 let mut b = package(&format!(
1754 "{}{section}",
1755 paragraph("Shared", "Revised source keeps inherited list formatting")
1756 ));
1757 a.set_part("word/styles.xml", styles_root(&a_styles).into_bytes());
1758 b.set_part(
1759 "word/styles.xml",
1760 styles_root(&format!("{b_style}{base}{run}")).into_bytes(),
1761 );
1762 let actual_a_numbering = if alternate_prefix {
1763 a_numbering
1764 .replace("w:", "n:")
1765 .replace("xmlns:w=", "xmlns:n=")
1766 } else {
1767 a_numbering.clone()
1768 };
1769 a.set_part(
1770 "word/numbering.xml",
1771 actual_a_numbering.replace('\'', "\"").into_bytes(),
1772 );
1773 b.set_part("word/numbering.xml", b_numbering.clone().into_bytes());
1774 for pkg in [&mut a, &mut b] {
1775 pkg.add_content_type_override(
1776 "/word/numbering.xml",
1777 "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
1778 );
1779 if !pkg.read_rels_for("word/document.xml").is_some_and(|rels| {
1780 rels.items
1781 .iter()
1782 .any(|r| r.rel_type.ends_with("/numbering"))
1783 }) {
1784 pkg.add_document_relationship(
1785 "word/document.xml",
1786 &format!("{RELS}/numbering"),
1787 "numbering.xml",
1788 );
1789 }
1790 }
1791 let a_bytes = a.to_zip().unwrap();
1792 let b_bytes = b.to_zip().unwrap();
1793 let output = append_documents(
1794 &a_bytes,
1795 &b_bytes,
1796 &AppendOptions {
1797 section_break: SectionBreak::None,
1798 keep_sections: false,
1799 comments: AppendComments::Drop,
1800 },
1801 )
1802 .unwrap();
1803 assert!(output.warnings.is_empty());
1804 let out = PartFs::open(&output.docx).unwrap();
1805 let renamed = if second_collision {
1806 "SharedB2"
1807 } else {
1808 "SharedB"
1809 };
1810 assert_eq!(
1811 view(&out.part_string("word/document.xml").unwrap()),
1812 view(&document(&format!(
1813 "{original}{}{section}",
1814 paragraph(renamed, "Revised source keeps inherited list formatting")
1815 )))
1816 );
1817
1818 verify_styles_xml(&out, &b_style, renamed, &a_styles, base, run);
1819 verify_numbering_xml(
1820 &out,
1821 disabled_list,
1822 &a_numbering,
1823 &b_numbering,
1824 nsid,
1825 collision_nsid,
1826 alternate_prefix,
1827 );
1828
1829 assert_eq!(snapshot(&PartFs::open(&a_bytes).unwrap()), snapshot(&a));
1830 assert_eq!(snapshot(&PartFs::open(&b_bytes).unwrap()), snapshot(&b));
1831 }
1832
1833 #[test]
1834 fn append_resolves_inherited_lists_and_style_collisions_through_both_numbering_serializations()
1835 {
1836 for alternate_prefix in [false, true] {
1837 for disabled_list in [false, true] {
1838 for second_collision in [false, true] {
1839 for collision_nsid in [false, true] {
1840 check_style_collisions_for_permutation(
1841 alternate_prefix,
1842 disabled_list,
1843 second_collision,
1844 collision_nsid,
1845 );
1846 }
1847 }
1848 }
1849 }
1850 }
1851}