Skip to main content

sheetkit_xml/
content_types.rs

1//! \[Content_Types\].xml schema structures.
2//!
3//! Defines the content types for all parts in the OOXML package.
4
5use serde::{Deserialize, Serialize};
6
7use crate::namespaces;
8
9/// `[Content_Types].xml` root element.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(rename = "Types")]
12pub struct ContentTypes {
13    #[serde(rename = "@xmlns", default = "default_content_types_ns")]
14    pub xmlns: String,
15
16    #[serde(rename = "Default", default)]
17    pub defaults: Vec<ContentTypeDefault>,
18
19    #[serde(rename = "Override", default)]
20    pub overrides: Vec<ContentTypeOverride>,
21}
22
23/// Extension-based default content type mapping.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub struct ContentTypeDefault {
26    #[serde(rename = "@Extension")]
27    pub extension: String,
28
29    #[serde(rename = "@ContentType")]
30    pub content_type: String,
31}
32
33/// Path-specific content type override.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct ContentTypeOverride {
36    #[serde(rename = "@PartName")]
37    pub part_name: String,
38
39    #[serde(rename = "@ContentType")]
40    pub content_type: String,
41}
42
43impl Default for ContentTypes {
44    fn default() -> Self {
45        Self {
46            xmlns: namespaces::CONTENT_TYPES.to_string(),
47            defaults: vec![
48                ContentTypeDefault {
49                    extension: "rels".to_string(),
50                    content_type: mime_types::RELS.to_string(),
51                },
52                ContentTypeDefault {
53                    extension: "xml".to_string(),
54                    content_type: mime_types::XML.to_string(),
55                },
56            ],
57            overrides: vec![
58                ContentTypeOverride {
59                    part_name: "/xl/workbook.xml".to_string(),
60                    content_type: mime_types::WORKBOOK.to_string(),
61                },
62                ContentTypeOverride {
63                    part_name: "/xl/worksheets/sheet1.xml".to_string(),
64                    content_type: mime_types::WORKSHEET.to_string(),
65                },
66                ContentTypeOverride {
67                    part_name: "/xl/styles.xml".to_string(),
68                    content_type: mime_types::STYLES.to_string(),
69                },
70                ContentTypeOverride {
71                    part_name: "/xl/sharedStrings.xml".to_string(),
72                    content_type: mime_types::SHARED_STRINGS.to_string(),
73                },
74            ],
75        }
76    }
77}
78
79/// Standard content type MIME string constants.
80pub mod mime_types {
81    // Default extensions
82    pub const RELS: &str = "application/vnd.openxmlformats-package.relationships+xml";
83    pub const XML: &str = "application/xml";
84    pub const PNG: &str = "image/png";
85    pub const JPEG: &str = "image/jpeg";
86    pub const GIF: &str = "image/gif";
87    pub const BMP: &str = "image/bmp";
88    pub const ICO: &str = "image/x-icon";
89    pub const TIFF: &str = "image/tiff";
90    pub const SVG: &str = "image/svg+xml";
91    pub const EMF: &str = "image/x-emf";
92    pub const EMZ: &str = "image/x-emz";
93    pub const WMF: &str = "image/x-wmf";
94    pub const WMZ: &str = "image/x-wmz";
95
96    // Workbook
97    pub const WORKBOOK: &str =
98        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
99    pub const WORKBOOK_MACRO: &str = "application/vnd.ms-excel.sheet.macroEnabled.main+xml";
100    pub const WORKBOOK_TEMPLATE: &str =
101        "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml";
102    pub const WORKBOOK_TEMPLATE_MACRO: &str =
103        "application/vnd.ms-excel.template.macroEnabled.main+xml";
104    pub const WORKBOOK_ADDIN_MACRO: &str = "application/vnd.ms-excel.addin.macroEnabled.main+xml";
105
106    // Worksheet
107    pub const WORKSHEET: &str =
108        "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
109    pub const CHARTSHEET: &str =
110        "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml";
111
112    // Shared elements
113    pub const SHARED_STRINGS: &str =
114        "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
115    pub const STYLES: &str =
116        "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
117    pub const THEME: &str = "application/vnd.openxmlformats-officedocument.theme+xml";
118
119    // Charts and drawings
120    pub const CHART: &str = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml";
121    pub const DRAWING: &str = "application/vnd.openxmlformats-officedocument.drawing+xml";
122
123    // Table
124    pub const TABLE: &str = "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml";
125
126    // VML Drawing
127    pub const VML_DRAWING: &str = "application/vnd.openxmlformats-officedocument.vmlDrawing";
128
129    // Form controls
130    pub const CONTROL_PROPERTIES: &str = "application/vnd.ms-excel.controlproperties+xml";
131
132    // Comments
133    pub const COMMENTS: &str =
134        "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml";
135
136    // Pivot tables
137    pub const PIVOT_TABLE: &str =
138        "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml";
139    pub const PIVOT_CACHE_DEFINITION: &str =
140        "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml";
141    pub const PIVOT_CACHE_RECORDS: &str =
142        "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml";
143
144    // Slicers
145    pub const SLICER: &str = "application/vnd.ms-excel.slicer+xml";
146    pub const SLICER_CACHE: &str = "application/vnd.ms-excel.slicerCache+xml";
147
148    // Document properties
149    pub const CORE_PROPERTIES: &str = "application/vnd.openxmlformats-package.core-properties+xml";
150    pub const EXTENDED_PROPERTIES: &str =
151        "application/vnd.openxmlformats-officedocument.extended-properties+xml";
152    pub const CUSTOM_PROPERTIES: &str =
153        "application/vnd.openxmlformats-officedocument.custom-properties+xml";
154}
155
156fn default_content_types_ns() -> String {
157    namespaces::CONTENT_TYPES.to_string()
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn test_content_types_default() {
166        let ct = ContentTypes::default();
167        assert_eq!(ct.xmlns, namespaces::CONTENT_TYPES);
168        assert_eq!(ct.defaults.len(), 2);
169        assert_eq!(ct.overrides.len(), 4);
170
171        // Check default extensions
172        assert_eq!(ct.defaults[0].extension, "rels");
173        assert_eq!(ct.defaults[1].extension, "xml");
174
175        // Check overrides contain workbook, worksheet, styles, shared strings
176        let part_names: Vec<&str> = ct.overrides.iter().map(|o| o.part_name.as_str()).collect();
177        assert!(part_names.contains(&"/xl/workbook.xml"));
178        assert!(part_names.contains(&"/xl/worksheets/sheet1.xml"));
179        assert!(part_names.contains(&"/xl/styles.xml"));
180        assert!(part_names.contains(&"/xl/sharedStrings.xml"));
181    }
182
183    #[test]
184    fn test_content_types_roundtrip() {
185        let ct = ContentTypes::default();
186        let xml = quick_xml::se::to_string(&ct).unwrap();
187        let parsed: ContentTypes = quick_xml::de::from_str(&xml).unwrap();
188        assert_eq!(ct.defaults.len(), parsed.defaults.len());
189        assert_eq!(ct.overrides.len(), parsed.overrides.len());
190        assert_eq!(ct.xmlns, parsed.xmlns);
191    }
192
193    #[test]
194    fn test_content_types_serialize_structure() {
195        let ct = ContentTypes::default();
196        let xml = quick_xml::se::to_string(&ct).unwrap();
197
198        // Should contain Types as root element
199        assert!(xml.contains("<Types"));
200        assert!(xml.contains("xmlns="));
201        // Should contain Default elements
202        assert!(xml.contains("<Default"));
203        assert!(xml.contains("Extension="));
204        assert!(xml.contains("ContentType="));
205        // Should contain Override elements
206        assert!(xml.contains("<Override"));
207        assert!(xml.contains("PartName="));
208    }
209
210    #[test]
211    fn test_parse_real_excel_content_types() {
212        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
213<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
214  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
215  <Default Extension="xml" ContentType="application/xml"/>
216  <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
217  <Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
218  <Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
219  <Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>
220</Types>"#;
221
222        let parsed: ContentTypes = quick_xml::de::from_str(xml).unwrap();
223        assert_eq!(parsed.defaults.len(), 2);
224        assert_eq!(parsed.overrides.len(), 4);
225        assert_eq!(parsed.defaults[0].extension, "rels");
226        assert_eq!(parsed.overrides[0].part_name, "/xl/workbook.xml");
227    }
228
229    #[test]
230    fn test_content_type_default_fields() {
231        let default = ContentTypeDefault {
232            extension: "png".to_string(),
233            content_type: mime_types::PNG.to_string(),
234        };
235        let xml = quick_xml::se::to_string(&default).unwrap();
236        assert!(xml.contains("Extension=\"png\""));
237        assert!(xml.contains("ContentType=\"image/png\""));
238    }
239}