ooxml_core/opc/package.rs
1//! `OpcPackage`:包加载/保存。
2//!
3//! 本文件是 OPC 容器层的入口。它把"加载/保存一个 `.pptx`"和"注册 part +
4//! 维护 Content-Types + 维护关系链"三个动作统一到 [`OpcPackage`] 一个类型上。
5//!
6//! # 加载流程
7//!
8//! 1. 打开文件 → `zip::ZipArchive`;
9//! 2. 读取 `[Content_Types].xml` → `ContentTypes` 模型;
10//! 3. 遍历 zip 全部条目,把每个 part 装入 `parts: BTreeMap<PartName, Part>`;
11//! 4. 关系文件 `.rels` 同样作为 part 装入(content-type 固定为
12//! `application/vnd...relationships+xml`)。
13//!
14//! # 保存流程
15//!
16//! 1. 创建 `zip::ZipWriter`;
17//! 2. 写 `[Content_Types].xml`(序列化 [`ContentTypes`]);
18//! 3. 按 partname 顺序遍历 `parts`,逐个写入 zip;
19//! 4. 关闭 zip。
20//!
21//! # 设计取舍
22//!
23//! - **不维护反向关系索引**:本结构只持有"由 partname 找 part"的正向映射;
24//! 反向"由 partname 找关系链"由调用方在 `Relationships` 上自行迭代。
25//! - **`BTreeMap` 而非 `HashMap`**:让 `iter_parts()` 总是按 partname 字典序
26//! 输出,便于 byte-diff 测试与稳定写入顺序。
27//! - **不解析 `.rels`**:关系文件以原始 blob 形式保留,调用方在需要时
28//! 调用 `Relationships::from_xml` 显式解析。
29
30use std::collections::BTreeMap;
31use std::fs::File;
32use std::io::{Read, Write};
33use std::path::Path;
34
35use super::content_types::{ContentTypes, DefaultExt};
36use super::part::{Part, PartName};
37use super::rels::Relationship;
38
39/// 标准 Content-Type 常量集合(格式无关公共部分)。
40///
41/// 这些常量与 ECMA-376 / OOXML 规范一一对应,使用 `pub const` 暴露
42/// 便于在序列化时直接引用而无需硬编码字符串。
43///
44/// PPTX 特有常量(`PRESENTATION` / `SLIDE` / `SLIDE_LAYOUT` / `SLIDE_MASTER` /
45/// `NOTES_SLIDE` / `NOTES_MASTER` / `COMMENTS` / `COMMENT_AUTHORS`)保留在
46/// pptx-rs 主 crate 的 `opc::package::ct` 模块中,并通过
47/// `pub use ooxml_core::opc::ct::*;` 重导出本模块的通用常量。
48pub mod ct {
49 /// 根关系 Content-Type:`application/vnd.openxmlformats-package.relationships+xml`。
50 pub const RELATIONSHIPS: &str = "application/vnd.openxmlformats-package.relationships+xml";
51 /// 主题:`.../theme+xml`。
52 pub const THEME: &str = "application/vnd.openxmlformats-officedocument.theme+xml";
53 /// 核心属性(`cp:coreProperties`)。
54 pub const CORE_PROPS: &str = "application/vnd.openxmlformats-package.core-properties+xml";
55 /// 应用属性(`extended-properties`)。
56 pub const APP_PROPS: &str =
57 "application/vnd.openxmlformats-officedocument.extended-properties+xml";
58 /// 自定义属性(`custom-properties`,`/docProps/custom.xml`)。
59 ///
60 /// 对应 OOXML 中 `Properties` 根元素,命名空间为
61 /// `http://schemas.openxmlformats.org/officeDocument/2006/custom-properties`。
62 pub const CUSTOM_PROPS: &str =
63 "application/vnd.openxmlformats-officedocument.custom-properties+xml";
64 /// 图表:`.../drawingml.chart+xml`(`/ppt/charts/chartN.xml`)。
65 ///
66 /// 对应 OOXML 中 `<c:chartSpace>` 根元素,命名空间为
67 /// `http://schemas.openxmlformats.org/drawingml/2006/chart`。
68 pub const CHART: &str = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml";
69 /// OLE 对象:`.../oleobject`(`/ppt/embeddings/oleObjectN.bin`,TODO-043)。
70 ///
71 /// 对应二进制 OLE 复合文档(CFB),被 slide 的 `<p:oleObj r:id="..."/>` 引用。
72 /// Content-Type 固定为 `application/vnd.openxmlformats-officedocument.oleobject`,
73 /// 与文件扩展名无关(PowerPoint 通过 progId 区分具体 OLE 服务器)。
74 pub const OLE_OBJECT: &str = "application/vnd.openxmlformats-officedocument.oleobject";
75 /// 嵌入式 Excel 工作簿:`.../spreadsheetml.sheet`(`/ppt/embeddings/Microsoft_Excel_WorksheetN.xlsx`,TODO-004 Excel 嵌入)。
76 ///
77 /// 对应 ECMA-376 SpreadsheetML 包格式,被 chart 的
78 /// `<c:externalData r:id="..."/>` 引用。PowerPoint 打开图表时
79 /// 会从该 xlsx part 读取数据源("编辑数据" 会启动 Excel)。
80 pub const SPREADSHEET_XLSX: &str =
81 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
82 /// 视频:`video/mp4`(`/ppt/media/mediaN.mp4`,TODO-033)。
83 ///
84 /// MP4 是 PowerPoint 最通用的视频格式。其它视频格式(wmv/avi)使用各自 MIME。
85 pub const VIDEO_MP4: &str = "video/mp4";
86 /// 音频:`audio/mp3`(`/ppt/media/mediaN.mp3`,TODO-033)。
87 ///
88 /// MP3 是 PowerPoint 最通用的音频格式。其它音频格式(wav/aac)使用各自 MIME。
89 pub const AUDIO_MP3: &str = "audio/mp3";
90 /// SmartArt 数据:`.../drawingml.diagramData+xml`(`/ppt/diagrams/dataN.xml`,TODO-037)。
91 ///
92 /// 对应 OOXML 中 `<dgm:dataModel>` 根元素,命名空间为
93 /// `http://schemas.openxmlformats.org/drawingml/2006/diagram`。
94 /// 被 slide 的 `<p:graphicFrame>` 内 `<dgm:relIds r:dm="..."/>` 引用。
95 pub const DIAGRAM_DATA: &str =
96 "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml";
97 /// SmartArt 布局:`.../drawingml.diagramLayout+xml`(`/ppt/diagrams/layoutN.xml`,TODO-037)。
98 ///
99 /// 对应 OOXML 中 `<dgm:layoutDef>` 根元素,定义节点排列算法与拓扑。
100 pub const DIAGRAM_LAYOUT: &str =
101 "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml";
102 /// SmartArt 快速样式:`.../drawingml.diagramQuickStyle+xml`(`/ppt/diagrams/quickStylesN.xml`,TODO-037)。
103 ///
104 /// 对应 OOXML 中 `<dgm:styleData>` 根元素,定义节点/连接线视觉样式。
105 pub const DIAGRAM_QUICK_STYLE: &str =
106 "application/vnd.openxmlformats-officedocument.drawingml.diagramQuickStyle+xml";
107 /// SmartArt 颜色:`.../drawingml.diagramColors+xml`(`/ppt/diagrams/colorsN.xml`,TODO-037)。
108 ///
109 /// 对应 OOXML 中 `<dgm:colorsDef>` 根元素,定义颜色变体映射。
110 pub const DIAGRAM_COLORS: &str =
111 "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml";
112}
113
114/// 一个 OPC 包。
115///
116/// 内部包含:
117/// - `parts`:所有 part 的字典(key 为 partname 字符串);
118/// - `content_types`:根 `[Content_Types].xml` 的强类型模型。
119#[derive(Debug, Clone, Default)]
120pub struct OpcPackage {
121 /// 所有 part(partname → Part),按 partname 字典序排列。
122 pub parts: BTreeMap<String, Part>,
123 /// ContentTypes 模型。
124 pub content_types: ContentTypes,
125}
126
127impl OpcPackage {
128 /// 构造空包(含默认 ContentTypes)。
129 pub fn new() -> Self {
130 OpcPackage {
131 parts: BTreeMap::new(),
132 content_types: ContentTypes::new_default(),
133 }
134 }
135
136 /// 放入一个 part(覆盖同名)。
137 ///
138 /// 在插入前会调用 [`Part::contribute_to`],由 part 自己决定如何
139 /// 更新 Content-Types(添加 override 等)。
140 pub fn put_part(&mut self, p: Part) {
141 p.contribute_to(&mut self.content_types);
142 self.parts.insert(p.partname.as_str().to_string(), p);
143 }
144
145 /// 取一个 part 的不可变引用。
146 pub fn get_part(&self, partname: &str) -> Option<&Part> {
147 self.parts.get(partname)
148 }
149
150 /// 取一个 part 的可变引用。
151 pub fn get_part_mut(&mut self, partname: &str) -> Option<&mut Part> {
152 self.parts.get_mut(partname)
153 }
154
155 /// 列出所有 part。
156 pub fn iter_parts(&self) -> impl Iterator<Item = &Part> {
157 self.parts.values()
158 }
159
160 /// part 数量。
161 pub fn part_count(&self) -> usize {
162 self.parts.len()
163 }
164
165 /// 加载 `.pptx`(zip 文件)。
166 ///
167 /// # 流程
168 /// 1. 读取 `[Content_Types].xml` 并解析;
169 /// 2. 遍历 zip 全部条目,把非目录、非 `[Content_Types].xml` 的条目
170 /// 装入 `parts`。
171 ///
172 /// # 错误
173 /// - `Error::Io`:文件读取失败;
174 /// - `Error::Zip`:zip 解压失败;
175 /// - `Error::Xml`:`[Content_Types].xml` 解析失败。
176 pub fn load(path: impl AsRef<Path>) -> crate::Result<Self> {
177 let file = File::open(path.as_ref())?;
178 let mut zip = zip::ZipArchive::new(file)?;
179 let mut pkg = OpcPackage::new();
180
181 // 1) 先读 [Content_Types].xml
182 let mut ct_xml = String::new();
183 zip.by_name("[Content_Types].xml")?
184 .read_to_string(&mut ct_xml)?;
185 pkg.content_types = parse_content_types_public(&ct_xml)?;
186
187 // 2) 读所有 part
188 for i in 0..zip.len() {
189 let mut entry = zip.by_index(i)?;
190 let name = entry.name().to_string();
191 if name == "[Content_Types].xml" {
192 continue;
193 }
194 if entry.is_dir() {
195 continue;
196 }
197
198 // 关系文件 (单独维护) 仍以 part 形式加入,但 content_type 固定
199 let mut blob = Vec::with_capacity(entry.size() as usize);
200 entry.read_to_end(&mut blob)?;
201 let ct = if name.ends_with(".rels") {
202 ct::RELATIONSHIPS.to_string()
203 } else {
204 derive_content_type(&pkg.content_types, &format!("/{}", name))
205 };
206 let partname = format!("/{}", name);
207 let part = Part::new(PartName::from_unchecked(partname), ct, blob);
208 pkg.parts.insert(part.partname.as_str().to_string(), part);
209 }
210 Ok(pkg)
211 }
212
213 /// 保存为 `.pptx`。
214 ///
215 /// 写入顺序:先 `[Content_Types].xml`,再按字典序遍历所有 part。
216 /// 所有条目使用 `deflate` 压缩 + `0o644` Unix 权限。
217 pub fn save(&self, path: impl AsRef<Path>) -> crate::Result<()> {
218 let file = File::create(path.as_ref())?;
219 let mut zip = zip::ZipWriter::new(file);
220 let opts: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
221 .compression_method(zip::CompressionMethod::Deflated)
222 .unix_permissions(0o644);
223
224 // 1) [Content_Types].xml
225 zip.start_file("[Content_Types].xml", opts)?;
226 zip.write_all(self.content_types.to_xml().as_bytes())?;
227
228 // 2) 其余 part
229 for part in self.parts.values() {
230 let p = part.partname.to_zip_path();
231 zip.start_file(p, opts)?;
232 zip.write_all(&part.blob)?;
233 }
234 zip.finish()?;
235 Ok(())
236 }
237
238 /// 写回内存 zip(用于测试)。
239 pub fn to_bytes(&self) -> crate::Result<Vec<u8>> {
240 use std::io::Cursor;
241 let mut buf: Vec<u8> = Vec::new();
242 {
243 let cursor = Cursor::new(&mut buf);
244 let mut zip = zip::ZipWriter::new(cursor);
245 let opts: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
246 .compression_method(zip::CompressionMethod::Deflated);
247 zip.start_file("[Content_Types].xml", opts)?;
248 zip.write_all(self.content_types.to_xml().as_bytes())?;
249 for part in self.parts.values() {
250 zip.start_file(part.partname.to_zip_path(), opts)?;
251 zip.write_all(&part.blob)?;
252 }
253 zip.finish()?;
254 }
255 Ok(buf)
256 }
257}
258
259/// 在 ContentTypes 中根据 partname 查找 Content-Type(override 优先)。
260///
261/// 顺序:先查 `overrides`(按 partname 完全匹配),再查 `defaults`(按扩展名)。
262/// 全部未命中则回退到 `application/octet-stream`。
263///
264/// # 用途
265/// - 在 [`OpcPackage::load`] / `Presentation::load_bytes` 之后,
266/// 对新加入 `parts` 的非 `.rels` 元素推断 content_type;
267/// - 在 `to_opc_package` 中也可以用,但通常**不需要**——写路径下
268/// `Part::contribute_to` 会主动调用 [`Part`] 的 `put_part` 自动写 override。
269pub fn derive_content_type(ct: &ContentTypes, partname: &str) -> String {
270 for o in &ct.overrides {
271 if o.partname == partname {
272 return o.content_type.clone();
273 }
274 }
275 // 用扩展名查 defaults
276 let ext = match partname.rfind('.') {
277 Some(i) => &partname[i + 1..],
278 None => "",
279 };
280 for d in &ct.defaults {
281 if d.extension == ext {
282 return d.content_type.clone();
283 }
284 }
285 "application/octet-stream".to_string()
286}
287
288/// 极简解析 `[Content_Types].xml`,主要提取 override。
289///
290/// 完整 schema 还支持 `<Default Extension="..." ContentType="..."/>` 与
291/// `<Override PartName="..." ContentType="..."/>` 两种元素,本函数
292/// 同时识别两者。
293pub fn parse_content_types_public(xml: &str) -> crate::Result<ContentTypes> {
294 use quick_xml::events::Event;
295 use quick_xml::reader::Reader;
296 let mut ct = ContentTypes::new_default();
297 let mut rd = Reader::from_str(xml);
298 rd.config_mut().trim_text(true);
299 let mut buf = Vec::new();
300 loop {
301 match rd.read_event_into(&mut buf) {
302 Ok(Event::Empty(e)) => {
303 let name = e.name();
304 match name.as_ref() {
305 b"Default" => {
306 let mut ext = None;
307 let mut ctype = None;
308 for a in e.attributes().flatten() {
309 match a.key.as_ref() {
310 b"Extension" => {
311 ext = a
312 .normalized_value(quick_xml::XmlVersion::Implicit1_0)
313 .ok()
314 .map(|v| v.to_string())
315 }
316 b"ContentType" => {
317 ctype = a
318 .normalized_value(quick_xml::XmlVersion::Implicit1_0)
319 .ok()
320 .map(|v| v.to_string())
321 }
322 _ => {}
323 }
324 }
325 if let (Some(ext), Some(ctype)) = (ext, ctype) {
326 ct.defaults.push(DefaultExt::new(ext, ctype));
327 }
328 }
329 b"Override" => {
330 let mut partname = None;
331 let mut ctype = None;
332 for a in e.attributes().flatten() {
333 match a.key.as_ref() {
334 b"PartName" => {
335 partname = a
336 .normalized_value(quick_xml::XmlVersion::Implicit1_0)
337 .ok()
338 .map(|v| v.to_string())
339 }
340 b"ContentType" => {
341 ctype = a
342 .normalized_value(quick_xml::XmlVersion::Implicit1_0)
343 .ok()
344 .map(|v| v.to_string())
345 }
346 _ => {}
347 }
348 }
349 if let (Some(p), Some(c)) = (partname, ctype) {
350 ct.add_override(&p, &c);
351 }
352 }
353 _ => {}
354 }
355 }
356 Ok(Event::Eof) => break,
357 Err(e) => return Err(crate::Error::Xml(format!("content-types parse: {e}"))),
358 _ => {}
359 }
360 buf.clear();
361 }
362 Ok(ct)
363}
364
365/// 工具:把一个 PartName 映射成 zip 内的"关系文件"路径。
366///
367/// 严格遵循 OPC 约定:`/ppt/slides/slide1.xml` 的关系文件应在
368/// `/ppt/slides/_rels/slide1.xml.rels`。
369///
370/// # 示例
371/// - `/ppt/slides/slide1.xml` → `/ppt/slides/_rels/slide1.xml.rels`
372/// - `/word/document.xml` → `/word/_rels/document.xml.rels`
373/// - `/foo` → `/_rels/foo.rels`
374pub fn rels_partname_for(partname: &str) -> String {
375 let p = partname.trim_start_matches('/');
376 let last_slash = p.rfind('/');
377 match last_slash {
378 None => format!("/_rels/{}.rels", p),
379 // 父目录 _rels 文件名.rels
380 Some(i) => format!("/{}/_rels/{}.rels", &p[..i], &p[i + 1..]),
381 }
382}
383
384/// 工具:建立"父 part → (id, reltype, target)"链;返回每个 target 的下一个 rId。
385///
386/// 通过扫描已有关系 ID(如 `rId1` / `rId2` ...)找到最大编号,分配 `max+1`。
387/// prefix 必须以字符串形式给出,常用 `rId`。
388pub fn next_rid(existing: &[Relationship], prefix: &str) -> String {
389 let mut max = 0u32;
390 for r in existing {
391 if let Some(n) = r.id.strip_prefix(prefix) {
392 if let Ok(v) = n.parse::<u32>() {
393 if v > max {
394 max = v;
395 }
396 }
397 }
398 }
399 format!("{}{}", prefix, max + 1)
400}