rvt 0.4.0

Apache-2.0 clean-room reader for Autodesk Revit files (.rvt, .rfa, .rte, .rft) without Revit: metadata, previews and the embedded schema of 2016-2026 files, and typed elements with measured geometry from Revit 2024 and 2025 projects, exported as IFC4, glTF and plan SVG.
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
472
473
474
475
476
477
478
479
480
481
//! Parse the `PartAtom` OLE stream — plain Atom-format XML that Autodesk
//! uses to carry family metadata (title, category, taxonomy, links).
//!
//! Namespace: `urn:schemas-autodesk-com:partatom`

use crate::{Error, Result};
use quick_xml::Reader;
use quick_xml::XmlVersion;
use quick_xml::escape::resolve_predefined_entity;
use quick_xml::events::Event;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PartAtom {
    /// The last title-like element seen — on families the family type
    /// name (`0610 x 0915mm` on the reference sample), on project files a
    /// Project Information parameter-group name. Kept for compatibility;
    /// prefer [`Self::entry_title`] for the document's name.
    pub title: Option<String>,
    /// The Atom entry's own `<title>` (the first un-prefixed one): the
    /// document name Revit recorded, e.g. `racbasicsamplefamily`.
    #[serde(default)]
    pub entry_title: Option<String>,
    pub id: Option<String>,
    pub updated: Option<String>,
    pub taxonomies: Vec<Taxonomy>,
    pub categories: Vec<Category>,
    /// Autodesk OmniClass code (e.g. `23.40.20.14.17` = Furniture).
    pub omniclass: Option<String>,
    /// Raw XML for lossless pass-through if a downstream tool wants it.
    pub raw_xml: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Taxonomy {
    pub term: String,
    pub label: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Category {
    pub term: String,
    pub scheme: Option<String>,
}

impl PartAtom {
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        let raw_xml = std::str::from_utf8(data)
            .map_err(|e| Error::PartAtom(format!("invalid UTF-8: {e}")))?
            .to_string();

        let mut atom = PartAtom {
            raw_xml: raw_xml.clone(),
            ..Default::default()
        };
        let mut reader = Reader::from_str(&raw_xml);
        // Do not enable trim_text: quick-xml ≥0.38 streams entities as
        // separate `GeneralRef` events between `Text` fragments, and
        // per-fragment trimming would eat spaces adjacent to `&amp;` etc.
        // We trim the accumulated value once when flushing a field.

        enum State {
            Top,
            InTitle,
            InEntryTitle,
            InId,
            InUpdated,
            InTaxonomyTerm,
            InTaxonomyLabel,
        }

        let mut state = State::Top;
        let mut buf = Vec::new();
        let mut pending = String::new();
        let mut current_taxonomy: Option<Taxonomy> = None;
        let mut last_category_term: Option<String> = None;
        let mut last_category_scheme: Option<String> = None;

        // quick-xml 0.38+ no longer expands entities inside `Text`; they
        // arrive as `Event::GeneralRef`. Accumulate both, then flush on
        // the closing tag (matches prior `BytesText::unescape` behavior).
        let flush_pending = |pending: &mut String,
                             state: &State,
                             atom: &mut PartAtom,
                             current_taxonomy: &mut Option<Taxonomy>,
                             last_category_term: &mut Option<String>| {
            let text = std::mem::take(pending);
            let text = text.trim();
            if text.is_empty() {
                return;
            }
            let text = text.to_string();
            match state {
                State::InTitle => atom.title = Some(text),
                State::InEntryTitle => {
                    atom.entry_title = Some(text.clone());
                    atom.title = Some(text);
                }
                State::InId => atom.id = Some(text),
                State::InUpdated => atom.updated = Some(text),
                State::InTaxonomyTerm => {
                    if let Some(t) = current_taxonomy.as_mut() {
                        t.term = text;
                    } else {
                        *last_category_term = Some(text);
                    }
                }
                State::InTaxonomyLabel => {
                    if let Some(t) = current_taxonomy.as_mut() {
                        t.label = text;
                    }
                }
                State::Top => {}
            }
        };

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) => {
                    let name_owned = String::from_utf8_lossy(e.name().as_ref()).to_string();
                    let (prefix, local) = match name_owned.split_once(':') {
                        Some((p, l)) => (Some(p.to_string()), l.to_string()),
                        None => (None, name_owned.clone()),
                    };
                    match local.as_str() {
                        "title" if prefix.is_none() && atom.entry_title.is_none() => {
                            state = State::InEntryTitle
                        }
                        "title" => state = State::InTitle,
                        "id" => state = State::InId,
                        "updated" => state = State::InUpdated,
                        "taxonomy" => {
                            current_taxonomy = Some(Taxonomy {
                                term: String::new(),
                                label: String::new(),
                            })
                        }
                        "term" => {
                            // Used in both <taxonomy> and <category>; the
                            // text handler routes the captured value
                            // based on whether a current_taxonomy is
                            // open. Scheme lives on the <category>
                            // parent — do NOT overwrite
                            // last_category_scheme here.
                            state = State::InTaxonomyTerm;
                        }
                        "label" => state = State::InTaxonomyLabel,
                        "category" => {
                            last_category_scheme = e.attributes().find_map(|a| {
                                let a = a.ok()?;
                                if a.key.as_ref() == b"scheme" {
                                    a.normalized_value(XmlVersion::Implicit1_0)
                                        .ok()
                                        .map(|v| v.into_owned())
                                } else {
                                    None
                                }
                            });
                            last_category_term = None;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Text(e)) => {
                    if let Ok(decoded) = e.decode() {
                        pending.push_str(&decoded);
                    }
                }
                Ok(Event::GeneralRef(e)) => {
                    if let Ok(Some(ch)) = e.resolve_char_ref() {
                        pending.push(ch);
                    } else if let Ok(name) = e.decode() {
                        if let Some(val) = resolve_predefined_entity(&name) {
                            pending.push_str(val);
                        }
                    }
                }
                Ok(Event::End(e)) => {
                    flush_pending(
                        &mut pending,
                        &state,
                        &mut atom,
                        &mut current_taxonomy,
                        &mut last_category_term,
                    );
                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
                    let local = name.rsplit(':').next().unwrap_or(&name).to_string();
                    match local.as_str() {
                        "taxonomy" => {
                            if let Some(t) = current_taxonomy.take() {
                                atom.taxonomies.push(t);
                            }
                        }
                        "category" => {
                            if let Some(term) = last_category_term.take() {
                                // OmniClass codes are numeric dotted identifiers like "23.40.20.14.17"
                                if term.chars().all(|c| c.is_ascii_digit() || c == '.')
                                    && term.contains('.')
                                {
                                    atom.omniclass.get_or_insert(term.clone());
                                }
                                atom.categories.push(Category {
                                    term,
                                    scheme: last_category_scheme.clone(),
                                });
                            }
                            last_category_scheme = None;
                        }
                        _ => {}
                    }
                    state = State::Top;
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(Error::PartAtom(format!("{e}"))),
                _ => {}
            }
            buf.clear();
        }

        Ok(atom)
    }

    /// Encode a `PartAtom` back to Atom-format XML bytes (WRT-08).
    /// Inverse of [`Self::from_bytes`].
    ///
    /// The writer emits UTF-8 XML with the Autodesk schema
    /// declarations:
    ///
    /// ```xml
    /// <?xml version="1.0" encoding="UTF-8"?>
    /// <entry xmlns="http://www.w3.org/2005/Atom"
    ///        xmlns:A="urn:schemas-autodesk-com:partatom">
    ///   <title>...</title>
    ///   <id>...</id>
    ///   <updated>...</updated>
    ///   <A:taxonomy><term>...</term><label>...</label></A:taxonomy>
    ///   <category><term>...</term><scheme>...</scheme></category>
    /// </entry>
    /// ```
    ///
    /// Optional fields (`title`, `id`, `updated`, plus each taxonomy
    /// and category) are omitted when `None` / empty. Text content
    /// is XML-escaped so special characters (`<`, `>`, `&`, quotes)
    /// survive the round-trip. Emits one element per line with a
    /// two-space indent for diff-friendly output.
    ///
    /// Round-trip guarantee: `PartAtom::from_bytes(&atom.encode())`
    /// preserves `title`, `id`, `updated`, every `Taxonomy`, every
    /// `Category`, and `omniclass`. `raw_xml` will differ (it's the
    /// reconstructed text, not a byte-echo of the original input).
    pub fn encode(&self) -> Vec<u8> {
        let mut out = String::with_capacity(256);
        out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        out.push_str(
            "<entry xmlns=\"http://www.w3.org/2005/Atom\" \
             xmlns:A=\"urn:schemas-autodesk-com:partatom\">\n",
        );
        if let Some(t) = self.title.as_deref() {
            out.push_str("  <title>");
            out.push_str(&xml_escape_text(t));
            out.push_str("</title>\n");
        }
        if let Some(id) = self.id.as_deref() {
            out.push_str("  <id>");
            out.push_str(&xml_escape_text(id));
            out.push_str("</id>\n");
        }
        if let Some(u) = self.updated.as_deref() {
            out.push_str("  <updated>");
            out.push_str(&xml_escape_text(u));
            out.push_str("</updated>\n");
        }
        for tax in &self.taxonomies {
            out.push_str("  <A:taxonomy><term>");
            out.push_str(&xml_escape_text(&tax.term));
            out.push_str("</term><label>");
            out.push_str(&xml_escape_text(&tax.label));
            out.push_str("</label></A:taxonomy>\n");
        }
        for cat in &self.categories {
            out.push_str("  <category");
            if let Some(scheme) = cat.scheme.as_deref() {
                out.push_str(" scheme=\"");
                out.push_str(&xml_escape_text(scheme));
                out.push('"');
            }
            out.push_str("><term>");
            out.push_str(&xml_escape_text(&cat.term));
            out.push_str("</term></category>\n");
        }
        out.push_str("</entry>\n");
        out.into_bytes()
    }
}

fn xml_escape_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            other => out.push(other),
        }
    }
    out
}

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

    #[test]
    fn parses_sample_partatom() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:A="urn:schemas-autodesk-com:partatom">
<title>racbasicsamplefamily</title>
<id>Table-End-0000-CAN-ENU</id>
<updated>2023-03-27T11:56:02Z</updated>
<A:taxonomy><term>adsk:revit</term><label>Autodesk Revit</label></A:taxonomy>
<category><term>23.40.20.14.17</term><scheme>std:oc1</scheme></category>
<category><term>Furniture</term><scheme>adsk:revit:grouping</scheme></category>
</entry>"#;
        let atom = PartAtom::from_bytes(xml.as_bytes()).unwrap();
        assert_eq!(atom.title.as_deref(), Some("racbasicsamplefamily"));
        assert_eq!(atom.omniclass.as_deref(), Some("23.40.20.14.17"));
        assert_eq!(atom.categories.len(), 2);
        assert_eq!(atom.taxonomies.len(), 1);
        assert_eq!(atom.taxonomies[0].label, "Autodesk Revit");
    }

    // ---- WRT-08: PartAtom writer round-trip ----

    fn sample_atom() -> PartAtom {
        PartAtom {
            title: Some("racbasicsamplefamily".into()),
            entry_title: Some("racbasicsamplefamily".into()),
            id: Some("Table-End-0000-CAN-ENU".into()),
            updated: Some("2023-03-27T11:56:02Z".into()),
            taxonomies: vec![Taxonomy {
                term: "adsk:revit".into(),
                label: "Autodesk Revit".into(),
            }],
            categories: vec![
                Category {
                    term: "23.40.20.14.17".into(),
                    scheme: Some("std:oc1".into()),
                },
                Category {
                    term: "Furniture".into(),
                    scheme: Some("adsk:revit:grouping".into()),
                },
            ],
            omniclass: Some("23.40.20.14.17".into()),
            raw_xml: String::new(),
        }
    }

    #[test]
    fn encode_round_trips_full_sample() {
        let original = sample_atom();
        let bytes = original.encode();
        let decoded = PartAtom::from_bytes(&bytes).unwrap();
        assert_eq!(decoded.title, original.title);
        assert_eq!(decoded.id, original.id);
        assert_eq!(decoded.updated, original.updated);
        assert_eq!(decoded.taxonomies.len(), original.taxonomies.len());
        assert_eq!(decoded.taxonomies[0].term, original.taxonomies[0].term);
        assert_eq!(decoded.taxonomies[0].label, original.taxonomies[0].label);
        assert_eq!(decoded.categories.len(), original.categories.len());
        assert_eq!(decoded.categories[0].term, original.categories[0].term);
        assert_eq!(decoded.categories[0].scheme, original.categories[0].scheme);
        assert_eq!(decoded.omniclass, original.omniclass);
    }

    #[test]
    fn encode_escapes_xml_special_chars() {
        let atom = PartAtom {
            title: Some("A & B <test>".into()),
            ..Default::default()
        };
        let bytes = atom.encode();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.contains("A &amp; B &lt;test&gt;"));
        let decoded = PartAtom::from_bytes(&bytes).unwrap();
        assert_eq!(decoded.title.as_deref(), Some("A & B <test>"));
    }

    #[test]
    fn encode_omits_missing_optional_fields() {
        let atom = PartAtom {
            title: Some("minimal".into()),
            ..Default::default()
        };
        let bytes = atom.encode();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.contains("<title>minimal</title>"));
        assert!(!s.contains("<id>"));
        assert!(!s.contains("<updated>"));
        assert!(!s.contains("<category>"));
        assert!(!s.contains("<A:taxonomy>"));
    }

    #[test]
    fn encode_emits_well_formed_xml_prolog() {
        let bytes = sample_atom().encode();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
        assert!(s.contains("xmlns=\"http://www.w3.org/2005/Atom\""));
        assert!(s.contains("xmlns:A=\"urn:schemas-autodesk-com:partatom\""));
        assert!(s.trim_end().ends_with("</entry>"));
    }

    #[test]
    fn encode_category_without_scheme_omits_scheme_tag() {
        let atom = PartAtom {
            categories: vec![Category {
                term: "Custom".into(),
                scheme: None,
            }],
            ..Default::default()
        };
        let bytes = atom.encode();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.contains("<category><term>Custom</term></category>"));
        assert!(!s.contains("<scheme>"));
    }

    #[test]
    fn xml_escape_covers_all_five_reserved_chars() {
        let s = xml_escape_text("<>&\"'");
        assert_eq!(s, "&lt;&gt;&amp;&quot;&apos;");
    }

    #[test]
    fn empty_atom_encodes_valid_minimal_document() {
        let bytes = PartAtom::default().encode();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(s.starts_with("<?xml"));
        assert!(s.contains("<entry"));
        assert!(s.contains("</entry>"));
        // Round-trips as an empty PartAtom.
        let decoded = PartAtom::from_bytes(&bytes).unwrap();
        assert!(decoded.title.is_none());
        assert!(decoded.taxonomies.is_empty());
        assert!(decoded.categories.is_empty());
    }

    #[test]
    fn later_title_element_replaces_earlier() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<title>racbasicsamplefamily</title>
<title>0610 x 0915mm</title>
</entry>"#;
        let atom = PartAtom::from_bytes(xml.as_bytes()).unwrap();
        assert_eq!(
            atom.title.as_deref(),
            Some("0610 x 0915mm"),
            "got {:?}",
            atom.title
        );
    }

    #[test]
    fn title_with_entity_chunks_still_concatenates() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<title>0610 &amp; 0915mm</title>
</entry>"#;
        let atom = PartAtom::from_bytes(xml.as_bytes()).unwrap();
        assert_eq!(
            atom.title.as_deref(),
            Some("0610 & 0915mm"),
            "got {:?}",
            atom.title
        );
    }
}