xmpkit 0.1.3

Pure Rust implementation of Adobe XMP Toolkit
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
//! XMP XML/RDF serializer
//!
//! This module provides functionality for serializing XMP metadata to XML/RDF format.

use crate::core::error::{XmpError, XmpResult};
use crate::core::namespace::{ns, NamespaceMap};
use crate::core::node::{ArrayNode, ArrayType, Node, StructureNode};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::Writer;
use std::io::Cursor;

/// Serializer for XMP Packets
pub struct XmpSerializer {
    namespaces: NamespaceMap,
}

impl XmpSerializer {
    /// Create a new XMP serializer
    pub fn new() -> Self {
        Self {
            namespaces: NamespaceMap::new(),
        }
    }

    /// Create a serializer with a pre-populated namespace map.
    pub fn with_namespaces(namespaces: NamespaceMap) -> Self {
        Self { namespaces }
    }

    /// Serialize a StructureNode to RDF/XML
    pub fn serialize_rdf(&self, root: &StructureNode) -> XmpResult<String> {
        let mut writer = Writer::new_with_indent(Cursor::new(Vec::new()), b' ', 2);

        // Collect namespaces used in the metadata
        let mut used_namespaces = std::collections::HashMap::new();

        // Collect simple nodes as attributes and complex nodes as elements
        let mut simple_attrs = Vec::new();
        let mut complex_nodes = Vec::new();

        for (key, node) in &root.fields {
            let parsed_path = self.parse_path_with_namespace(key);

            if let Some((prefix, _, ns_uri)) = &parsed_path {
                used_namespaces.insert(ns_uri.clone(), prefix.clone());
            }

            if self.should_serialize_as_element(key, node) {
                complex_nodes.push((key.clone(), node.clone()));
            } else if let Some((prefix, prop_name, _)) = parsed_path {
                if let Node::Simple(simple) = node {
                    simple_attrs.push((format!("{}:{}", prefix, prop_name), simple.value.clone()));
                } else {
                    complex_nodes.push((key.clone(), node.clone()));
                }
            }
        }

        // Write RDF root element with namespaces
        let mut rdf_start = BytesStart::new("rdf:RDF");
        rdf_start.push_attribute(("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
        rdf_start.push_attribute(("xmlns:xmp", "http://ns.adobe.com/xap/1.0/"));
        rdf_start.push_attribute(("xmlns:dc", "http://purl.org/dc/elements/1.1/"));
        rdf_start.push_attribute(("xmlns:exif", "http://ns.adobe.com/exif/1.0/"));
        rdf_start.push_attribute(("xmlns:xml", ns::XML));

        // Add dynamically discovered namespaces
        for (ns_uri, prefix) in &used_namespaces {
            // Skip namespaces already declared above
            match ns_uri.as_str() {
                "http://www.w3.org/1999/02/22-rdf-syntax-ns#" => continue,
                "http://ns.adobe.com/xap/1.0/" => continue,
                "http://purl.org/dc/elements/1.1/" => continue,
                "http://ns.adobe.com/exif/1.0/" => continue,
                ns::XML => continue,
                _ => {
                    rdf_start
                        .push_attribute((format!("xmlns:{}", prefix).as_str(), ns_uri.as_str()));
                }
            }
        }

        writer.write_event(Event::Start(rdf_start))?;

        // Write Description element with attributes and nested elements
        let mut desc_start = BytesStart::new("rdf:Description");
        desc_start.push_attribute(("rdf:about", ""));

        // Add simple attributes to Description
        for (attr_name, attr_value) in &simple_attrs {
            desc_start.push_attribute((attr_name.as_str(), attr_value.as_str()));
        }

        // If there are no complex nodes, use Empty (self-closing) tag
        // Otherwise use Start/End tags
        if complex_nodes.is_empty() {
            writer.write_event(Event::Empty(desc_start))?;
        } else {
            writer.write_event(Event::Start(desc_start))?;

            // Serialize complex nodes as nested elements
            for (key, node) in &complex_nodes {
                self.serialize_node(&mut writer, key, node)?;
            }

            writer.write_event(Event::End(BytesEnd::new("rdf:Description")))?;
        }
        writer.write_event(Event::End(BytesEnd::new("rdf:RDF")))?;

        let result = writer.into_inner().into_inner();
        String::from_utf8(result)
            .map_err(|e| XmpError::SerializationError(format!("UTF-8 encoding error: {}", e)))
    }

    /// Parse a path in format "namespace_uri:property_name" into (prefix, property_name, namespace_uri)
    ///
    /// This function converts the internal path format (namespace URI:property) to
    /// the serialization format (prefix:property). It follows C++ SDK behavior:
    /// - First checks instance namespace map
    /// - Then checks global namespace registry
    /// - Returns None if namespace is not registered (does not infer prefix from URI)
    fn parse_path_with_namespace(&self, path: &str) -> Option<(String, String, String)> {
        // Find the last colon (to handle URIs that contain colons like http://...)
        let colon_pos = path.rfind(':')?;
        let ns_uri = &path[..colon_pos];
        let prop_name = &path[colon_pos + 1..];

        // Try to get prefix from instance namespace map first
        if let Some(prefix) = self.namespaces.get_prefix(ns_uri) {
            return Some((
                prefix.to_string(),
                prop_name.to_string(),
                ns_uri.to_string(),
            ));
        }

        // Fallback: check global namespace registry
        use crate::core::namespace::get_global_namespace_prefix;
        if let Some(prefix) = get_global_namespace_prefix(ns_uri) {
            return Some((prefix, prop_name.to_string(), ns_uri.to_string()));
        }

        // Namespace not registered - return None (following C++ SDK behavior)
        // In C++ SDK, unregistered namespaces would cause an error during serialization
        None
    }

    /// Parse a path in format "namespace_uri:property_name" into (prefix, property_name)
    /// This is a compatibility method that calls parse_path_with_namespace
    fn parse_path(&self, path: &str) -> Option<(String, String)> {
        self.parse_path_with_namespace(path)
            .map(|(prefix, prop_name, _)| (prefix, prop_name))
    }

    /// Serialize a node
    fn serialize_node(
        &self,
        writer: &mut Writer<Cursor<Vec<u8>>>,
        path: &str,
        node: &Node,
    ) -> XmpResult<()> {
        match node {
            Node::Simple(simple) => {
                self.serialize_simple_node(writer, path, simple)?;
            }
            Node::Array(array) => {
                self.serialize_array_node(writer, path, array)?;
            }
            Node::Structure(structure) => {
                self.serialize_structure_node(writer, path, structure)?;
            }
        }
        Ok(())
    }

    /// Serialize a simple node
    fn serialize_simple_node(
        &self,
        writer: &mut Writer<Cursor<Vec<u8>>>,
        path: &str,
        node: &crate::core::node::SimpleNode,
    ) -> XmpResult<()> {
        let (prefix, prop_name) = self
            .parse_path(path)
            .ok_or_else(|| XmpError::BadXPath(format!("Invalid path format: {}", path)))?;

        let elem_name = format!("{}:{}", prefix, prop_name);
        let mut elem_start = BytesStart::new(&elem_name);

        // Add qualifiers as attributes (e.g., xml:lang)
        self.add_lang_qualifier_attributes(&Node::Simple(node.clone()), &mut elem_start);

        writer.write_event(Event::Start(elem_start))?;
        writer.write_event(Event::Text(BytesText::new(&node.value)))?;
        writer.write_event(Event::End(BytesEnd::new(&elem_name)))?;

        Ok(())
    }

    /// Serialize an array node
    fn serialize_array_node(
        &self,
        writer: &mut Writer<Cursor<Vec<u8>>>,
        path: &str,
        node: &ArrayNode,
    ) -> XmpResult<()> {
        let (prefix, prop_name) = self
            .parse_path(path)
            .ok_or_else(|| XmpError::BadXPath(format!("Invalid path format: {}", path)))?;

        let container_name = match node.array_type {
            ArrayType::Ordered => "rdf:Seq",
            ArrayType::Unordered => "rdf:Bag",
            ArrayType::Alternative => "rdf:Alt",
        };

        // Write property element containing the container
        let prop_elem = format!("{}:{}", prefix, prop_name);
        writer.write_event(Event::Start(BytesStart::new(&prop_elem)))?;

        // Write container element
        writer.write_event(Event::Start(BytesStart::new(container_name)))?;

        // Write list items
        for item in &node.items {
            let mut li_start = BytesStart::new("rdf:li");
            self.add_lang_qualifier_attributes(item, &mut li_start);
            writer.write_event(Event::Start(li_start))?;

            self.serialize_array_item(writer, item)?;

            writer.write_event(Event::End(BytesEnd::new("rdf:li")))?;
        }

        writer.write_event(Event::End(BytesEnd::new(container_name)))?;
        writer.write_event(Event::End(BytesEnd::new(&prop_elem)))?;
        Ok(())
    }

    /// Serialize a structure node
    fn serialize_structure_node(
        &self,
        writer: &mut Writer<Cursor<Vec<u8>>>,
        path: &str,
        node: &StructureNode,
    ) -> XmpResult<()> {
        let (prefix, prop_name) = self
            .parse_path(path)
            .ok_or_else(|| XmpError::BadXPath(format!("Invalid path format: {}", path)))?;

        // Write property element containing the structure
        let prop_elem = format!("{}:{}", prefix, prop_name);
        writer.write_event(Event::Start(BytesStart::new(&prop_elem)))?;

        // Write structure as nested Description with rdf:parseType="Resource"
        let mut desc_start = BytesStart::new("rdf:Description");
        desc_start.push_attribute(("rdf:parseType", "Resource"));
        writer.write_event(Event::Start(desc_start))?;

        // Write fields
        for (key, value) in &node.fields {
            self.serialize_node(writer, key, value)?;
        }

        writer.write_event(Event::End(BytesEnd::new("rdf:Description")))?;
        writer.write_event(Event::End(BytesEnd::new(&prop_elem)))?;
        Ok(())
    }

    /// Check if a node should be serialized as an element (not attribute)
    fn should_serialize_as_element(&self, _key: &str, node: &Node) -> bool {
        let Node::Simple(simple) = node else {
            // Arrays and structures are always elements
            return true;
        };

        // Simple nodes with xml:lang qualifier must be elements
        simple
            .qualifiers
            .iter()
            .any(|q| q.namespace == ns::XML && q.name == "lang")
    }

    /// Add language qualifier attributes to an element
    fn add_lang_qualifier_attributes(&self, node: &Node, elem_start: &mut BytesStart) {
        let Node::Simple(simple) = node else {
            return;
        };

        for qualifier in &simple.qualifiers {
            if qualifier.namespace == ns::XML && qualifier.name == "lang" {
                elem_start.push_attribute(("xml:lang", qualifier.value.as_str()));
            }
        }
    }

    /// Serialize an array item
    fn serialize_array_item(
        &self,
        writer: &mut Writer<Cursor<Vec<u8>>>,
        item: &Node,
    ) -> XmpResult<()> {
        match item {
            Node::Simple(simple) => {
                writer.write_event(Event::Text(BytesText::new(&simple.value)))?;
            }
            Node::Structure(structure) => {
                writer.write_event(Event::Start(BytesStart::new("rdf:Description")))?;
                for (key, value) in &structure.fields {
                    self.serialize_node(writer, key, value)?;
                }
                writer.write_event(Event::End(BytesEnd::new("rdf:Description")))?;
            }
            Node::Array(_) => {
                return Err(XmpError::NotSupported(
                    "Nested arrays not yet supported".to_string(),
                ));
            }
        }
        Ok(())
    }

    /// Serialize to XMP Packet format
    pub fn serialize_packet(&self, root: &StructureNode) -> XmpResult<String> {
        let rdf_content = self.serialize_rdf(root)?;

        // Wrap in xpacket
        let packet = format!(
            r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
{}
<?xpacket end="w"?>"#,
            rdf_content
        );

        Ok(packet)
    }

    /// Serialize to XMP Packet format with padding to reach a target length
    ///
    /// This is useful for in-place updates where the new packet needs to fit
    /// within the space of an existing packet.
    ///
    /// # Arguments
    ///
    /// * `root` - The root node to serialize
    /// * `target_length` - The desired total packet length in bytes
    ///
    /// # Returns
    ///
    /// * `Ok(String)` - The serialized packet with padding
    /// * `Err(XmpError)` - If the serialized packet exceeds target_length
    pub fn serialize_packet_with_padding(
        &self,
        root: &StructureNode,
        target_length: usize,
    ) -> XmpResult<String> {
        let rdf_content = self.serialize_rdf(root)?;

        // Calculate the overhead for the packet wrapper
        // <?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>\n ... \n<?xpacket end="w"?>
        let header = r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>"#;
        let trailer = r#"<?xpacket end="w"?>"#;

        // Calculate minimum length without padding
        let min_length = header.len() + 1 + rdf_content.len() + 1 + trailer.len();

        if min_length > target_length {
            return Err(XmpError::BadValue(format!(
                "XMP packet minimum size ({}) exceeds target length ({})",
                min_length, target_length
            )));
        }

        // Calculate padding needed
        let padding_needed = target_length - min_length;

        // Create padding (use spaces for simple padding, following XMP spec)
        // The padding goes between the RDF content and the trailer
        let padding = " ".repeat(padding_needed);

        let packet = format!("{}\n{}\n{}{}", header, rdf_content, padding, trailer);

        Ok(packet)
    }
}

impl Default for XmpSerializer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serialize_rdf() {
        let serializer = XmpSerializer::new();
        let root = StructureNode::new();
        let result = serializer.serialize_rdf(&root);
        assert!(result.is_ok());
    }

    #[test]
    fn test_serialize_packet() {
        let serializer = XmpSerializer::new();
        let mut root = StructureNode::new();
        root.set_field(
            "http://ns.adobe.com/xap/1.0/:CreatorTool".to_string(),
            Node::simple("TestApp".to_string()),
        );
        let result = serializer.serialize_packet(&root);
        assert!(result.is_ok());
        let packet = result.unwrap();
        eprintln!("Serialized packet:\n{}", packet);
        assert!(packet.contains("<?xpacket"));
        assert!(packet.contains("rdf:RDF"));
        assert!(packet.contains("xmp:CreatorTool"));
    }

    #[test]
    fn test_serialize_packet_with_padding() {
        let serializer = XmpSerializer::new();
        let mut root = StructureNode::new();
        root.set_field(
            "http://ns.adobe.com/xap/1.0/:CreatorTool".to_string(),
            Node::simple("TestApp".to_string()),
        );

        // First get the minimum packet size
        let min_packet = serializer.serialize_packet(&root).unwrap();
        let min_len = min_packet.len();

        // Test with target length equal to minimum (no padding needed)
        let result = serializer.serialize_packet_with_padding(&root, min_len);
        assert!(result.is_ok());
        let packet = result.unwrap();
        assert_eq!(packet.len(), min_len);
        assert!(packet.contains("<?xpacket"));
        assert!(packet.ends_with("<?xpacket end=\"w\"?>"));

        // Test with target length larger than minimum (padding added)
        let target_len = min_len + 100;
        let result = serializer.serialize_packet_with_padding(&root, target_len);
        assert!(result.is_ok());
        let packet = result.unwrap();
        assert_eq!(packet.len(), target_len);
        assert!(packet.contains("<?xpacket"));
        assert!(packet.ends_with("<?xpacket end=\"w\"?>"));
    }

    #[test]
    fn test_serialize_packet_with_padding_too_small() {
        let serializer = XmpSerializer::new();
        let mut root = StructureNode::new();
        root.set_field(
            "http://ns.adobe.com/xap/1.0/:CreatorTool".to_string(),
            Node::simple("TestApp".to_string()),
        );

        // Test with target length too small - should fail
        let result = serializer.serialize_packet_with_padding(&root, 10);
        assert!(result.is_err());

        // Verify error message
        let err = result.unwrap_err();
        let err_msg = err.to_string();
        assert!(err_msg.contains("exceeds target length"));
    }
}