Skip to main content

jubarte_redlines/
wml_document.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2// SPDX-FileCopyrightText: Microsoft Corporation
3// SPDX-FileCopyrightText: 2025-2026 John Scrudato IV
4//
5// SPDX-License-Identifier: Apache-2.0 AND LicenseRef-Docxodus-MIT
6
7//! Port of `WmlDocument` / `PtMainDocumentPart` (`WmlDocument.ts`) — M1.7.
8//!
9//! Models the C# `WmlDocument` surface the comparer uses: it carries
10//! `DocumentByteArray` and exposes the main document part (parsed into the arena
11//! DOM on demand). Backed by the M1.5 `PartFs` OPC layer.
12
13use crate::admission::{InputLimits, admit};
14use crate::opc::{OpcError, PartFs, refused};
15use crate::xmllinq::{Dom, NodeId};
16
17/// A WordprocessingML document held as its package bytes plus the main
18/// document part parsed on demand. Mirrors the C# `WmlDocument`
19/// (`DocumentByteArray` + lazy `MainDocumentPart`) used by the
20/// [`crate::comparer`] pipeline.
21///
22/// Constructed with [`Self::from_bytes`] (which admits under
23/// [`InputLimits::compare`](crate::admission::InputLimits::compare));
24/// reads and edits go through [`Self::dom`] / [`Self::dom_mut`] and
25/// [`Self::part_fs`] / [`Self::part_fs_mut`].
26pub struct WmlDocument {
27    /// `DocumentByteArray`: the bytes the document was opened from.
28    document_byte_array: Vec<u8>,
29    /// `FileName` — the inherited `WmlDocument` property, kept as a free
30    /// string for callers that gather metrics or build paths from it.
31    pub file_name: String,
32    part_fs: PartFs,
33    dom: Dom,
34    main_doc: Option<NodeId>,
35}
36
37impl WmlDocument {
38    /// Opens `bytes` as a `.docx`, admits it under
39    /// [`InputLimits::compare`](crate::admission::InputLimits::compare),
40    /// and lazily parses the main document part on the first
41    /// [`Self::main_document`] call.
42    ///
43    /// # Errors
44    ///
45    /// - `OpcError::Io` wrapping
46    ///   [`crate::admission::AdmissionError`] when admission refuses the
47    ///   bytes (a budget, a duplicate or unsafe part name, an encrypted
48    ///   package, an `.doc` or RTF that is not a `.docx`, or an XML part
49    ///   too deep or malformed).
50    /// - Any error [`PartFs::open`] reports (the standard OPC errors:
51    ///   [`OpcError::Zip`], [`OpcError::PartNotFound`], etc.).
52    pub fn from_bytes(bytes: &[u8]) -> Result<Self, OpcError> {
53        admit(bytes, InputLimits::compare()).map_err(refused)?;
54        Ok(WmlDocument {
55            document_byte_array: bytes.to_vec(),
56            file_name: String::new(),
57            part_fs: PartFs::open(bytes)?,
58            dom: Dom::new(),
59            main_doc: None,
60        })
61    }
62
63    /// The bytes the document was opened from. Edits through
64    /// [`Self::part_fs_mut`] or [`Self::dom_mut`] do not show here;
65    /// repack through [`crate::opc::PartFs::to_zip`] to get the new bytes.
66    pub fn bytes(&self) -> &[u8] {
67        &self.document_byte_array
68    }
69
70    /// The main document part name (`word/document.xml` unless OPC
71    /// relationships name otherwise). The string always returned even
72    /// when the part is absent.
73    pub fn main_document_part_name(&self) -> String {
74        self.part_fs
75            .main_document_part()
76            .unwrap_or_else(|| "word/document.xml".to_string())
77    }
78
79    /// Parses the main document part (once) and returns its document
80    /// node. Subsequent calls return the cached node.
81    ///
82    /// # Errors
83    ///
84    /// [`OpcError::PartNotFound`] when the package has no part at
85    /// [`Self::main_document_part_name`] (the body the comparer would
86    /// diff into is missing).
87    pub fn main_document(&mut self) -> Result<NodeId, OpcError> {
88        if let Some(id) = self.main_doc {
89            return Ok(id);
90        }
91        let name = self.main_document_part_name();
92        let xml = self
93            .part_fs
94            .part_string(&name)
95            .ok_or_else(|| OpcError::PartNotFound(name.clone()))?;
96        let doc = self.dom.parse_xdocument(&xml);
97        self.main_doc = Some(doc);
98        Ok(doc)
99    }
100
101    /// The root element (`<w:document>`) of the main document part.
102    ///
103    /// # Errors
104    ///
105    /// [`OpcError::PartNotFound`] when the part is absent, or the parsed
106    /// XML has no root element.
107    pub fn main_document_root(&mut self) -> Result<NodeId, OpcError> {
108        let doc = self.main_document()?;
109        let name = self.main_document_part_name();
110        self.dom
111            .root(doc)
112            .ok_or_else(|| OpcError::PartNotFound(format!("{name}: no root element")))
113    }
114
115    /// The arena DOM (read-only). Empty until a successful
116    /// [`Self::main_document`] parses the part into it.
117    pub fn dom(&self) -> &Dom {
118        &self.dom
119    }
120    /// The arena DOM (mutable). The comparer mutates this DOM while it
121    /// produces the body diff.
122    pub fn dom_mut(&mut self) -> &mut Dom {
123        &mut self.dom
124    }
125    /// The opened OPC package (read-only), by which every other part and
126    /// relationship is read.
127    pub fn part_fs(&self) -> &PartFs {
128        &self.part_fs
129    }
130    /// The opened OPC package (mutable).
131    pub fn part_fs_mut(&mut self) -> &mut PartFs {
132        &mut self.part_fs
133    }
134}