Skip to main content

deepdoc_core/extract/
odf.rs

1//! OpenDocument text and presentations (`.odt`, `.odp`).
2//!
3//! ODF puts the content in `content.xml` and the metadata in `meta.xml`.
4//! Structure is explicit — `text:h` carries its own outline level, `text:list`
5//! nests directly — but character styling is not: a `text:span` names a style
6//! whose weight and slant live in `office:automatic-styles`, so that table is
7//! read first.
8
9use std::collections::HashMap;
10use std::path::Path;
11
12use crate::detect::{Format, Sniff};
13use crate::error::{Error, Result};
14use crate::extract::container::Container;
15use crate::extract::xml::{self, Element};
16use crate::extract::{ExtractOpts, Extractor};
17use crate::model::{Block, Document, Inline, Metadata, Row, Span};
18
19/// Handles both `.odt` and `.odp`; the body element decides which is which.
20pub struct OdfExtractor;
21
22impl Extractor for OdfExtractor {
23    fn name(&self) -> &'static str {
24        "odf"
25    }
26
27    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
28        matches!(
29            crate::detect::detect(sniff),
30            Some(Format::Odt | Format::Odp)
31        )
32    }
33
34    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
35        let mut container = Container::open(path)?;
36
37        let content = container
38            .read("content.xml")
39            .map_err(|message| Error::parse(path, message))?;
40        let blocks = parse(&content).map_err(|message| Error::parse(path, message))?;
41
42        let mut meta = metadata(container.read_optional("meta.xml").as_deref());
43        meta.source_format = crate::detect::detect_path(path).ok();
44        meta.source_path = Some(path.display().to_string());
45
46        Ok(Document { meta, blocks })
47    }
48}
49
50/// Parse `content.xml` into blocks. Pure.
51pub fn parse(content: &str) -> std::result::Result<Vec<Block>, String> {
52    let root = xml::parse(content)?;
53    let styles = StyleTable::parse(&root);
54
55    let Some(body) = root.child("body") else {
56        return Ok(Vec::new());
57    };
58
59    // A presentation is a sequence of pages; a text document is one flow.
60    if let Some(presentation) = body.child("presentation") {
61        return Ok(pages(presentation, &styles));
62    }
63
64    let text = body.child("text").unwrap_or(body);
65    Ok(blocks(text, &styles))
66}
67
68/// Read `meta.xml` for the document's title and author.
69pub fn metadata(source: Option<&str>) -> Metadata {
70    let Some(root) = source.and_then(|source| xml::parse(source).ok()) else {
71        return Metadata::default();
72    };
73
74    let text_of = |name: &str| {
75        root.find(name)
76            .map(|element| element.text().trim().to_string())
77            .filter(|text| !text.is_empty())
78    };
79
80    // `<meta:document-statistic meta:page-count="12" …/>` — the editor's own
81    // count, which is the only honest one without laying the document out.
82    let page_count = root
83        .find("document-statistic")
84        .and_then(|statistic| statistic.attr_number("page-count"))
85        .and_then(|count| u32::try_from(count).ok())
86        .filter(|count| *count > 0);
87
88    Metadata {
89        title: text_of("title"),
90        author: text_of("creator").or_else(|| text_of("initial-creator")),
91        created: text_of("creation-date"),
92        language: text_of("language"),
93        page_count,
94        ..Metadata::default()
95    }
96}
97
98/// Each `draw:page` becomes a section, like a pptx slide.
99fn pages(presentation: &Element, styles: &StyleTable) -> Vec<Block> {
100    let mut out = Vec::new();
101
102    for (index, page) in presentation.find_all("page").into_iter().enumerate() {
103        let number = index + 1;
104        if number > 1 {
105            out.push(Block::PageBreak {
106                page: number as u32,
107            });
108        }
109
110        let mut content = blocks(page, styles);
111        // The first line of a slide is its title, as on a pptx slide.
112        let heading = match content.first() {
113            Some(Block::Paragraph { text }) => {
114                let text = text.clone();
115                content.remove(0);
116                text
117            }
118            _ => Inline::text(
119                page.attr("name")
120                    .map(str::to_string)
121                    .unwrap_or_else(|| format!("Slide {number}")),
122            ),
123        };
124
125        out.push(Block::Heading {
126            level: 2,
127            text: heading,
128        });
129        out.extend(content);
130    }
131
132    out
133}
134
135/// Walk a block container: the text body, a list item or a table cell.
136fn blocks(container: &Element, styles: &StyleTable) -> Vec<Block> {
137    let mut out = Vec::new();
138
139    for child in container.elements() {
140        match child.name.as_str() {
141            "h" => {
142                let level = child.attr_number("outline-level").unwrap_or(1).clamp(1, 6) as u8;
143                let text = inline(child, styles);
144                if !text.plain_text().trim().is_empty() {
145                    out.push(Block::Heading { level, text });
146                }
147            }
148            "p" => {
149                let text = inline(child, styles);
150                if !text.plain_text().trim().is_empty() {
151                    out.push(Block::Paragraph { text });
152                }
153                out.extend(images(child));
154            }
155            "list" => {
156                if let Some(list) = list_block(child, styles) {
157                    out.push(list);
158                }
159            }
160            "table" => {
161                if let Some(table) = table_block(child, styles) {
162                    out.push(table);
163                }
164            }
165            // Frames, sections and text boxes wrap content without adding any.
166            "frame" | "text-box" | "section" | "a" | "soft-page-break" => {
167                out.extend(blocks(child, styles));
168            }
169            _ => {}
170        }
171    }
172
173    out
174}
175
176fn list_block(list: &Element, styles: &StyleTable) -> Option<Block> {
177    let items: Vec<Vec<Block>> = list
178        .find_all("list-item")
179        .into_iter()
180        .map(|item| blocks(item, styles))
181        .filter(|blocks| !blocks.is_empty())
182        .collect();
183
184    if items.is_empty() {
185        return None;
186    }
187    Some(Block::List {
188        ordered: styles.is_ordered(list.attr("style-name").unwrap_or_default()),
189        items,
190    })
191}
192
193fn table_block(table: &Element, styles: &StyleTable) -> Option<Block> {
194    let mut rows: Vec<Row> = Vec::new();
195
196    for row in table.find_all("table-row") {
197        let cells: Vec<Inline> = row
198            .find_all("table-cell")
199            .into_iter()
200            .map(|cell| {
201                let text = blocks(cell, styles)
202                    .iter()
203                    .map(Block::plain_text)
204                    .collect::<Vec<_>>()
205                    .join(" ");
206                Inline::text(text.trim())
207            })
208            .collect();
209        if !cells.is_empty() {
210            rows.push(Row::new(cells));
211        }
212    }
213
214    if rows.is_empty() {
215        return None;
216    }
217    let header = rows.remove(0);
218    Some(Block::Table {
219        header: Some(header),
220        rows,
221    })
222}
223
224/// Collect the inline content of a paragraph or heading.
225fn inline(paragraph: &Element, styles: &StyleTable) -> Inline {
226    let mut spans = Vec::new();
227    collect_inline(paragraph, styles, &mut spans);
228    Inline::new(spans)
229}
230
231fn collect_inline(element: &Element, styles: &StyleTable, spans: &mut Vec<Span>) {
232    for child in &element.children {
233        match child {
234            xml::Node::Text(text) => spans.push(Span::Text(text.clone())),
235            xml::Node::Element(element) => match element.name.as_str() {
236                "span" => {
237                    let mut inner = Vec::new();
238                    collect_inline(element, styles, &mut inner);
239                    if inner.is_empty() {
240                        continue;
241                    }
242                    let style = element.attr("style-name").unwrap_or_default();
243                    spans.extend(styles.wrap(style, inner));
244                }
245                "a" => {
246                    let mut inner = Vec::new();
247                    collect_inline(element, styles, &mut inner);
248                    match element.attr("href") {
249                        Some(href) if !inner.is_empty() => spans.push(Span::Link {
250                            href: href.to_string(),
251                            text: inner,
252                        }),
253                        _ => spans.extend(inner),
254                    }
255                }
256                "line-break" => spans.push(Span::LineBreak),
257                "tab" => spans.push(Span::Text("\t".into())),
258                // `<text:s text:c="3"/>` is a run of spaces.
259                "s" => {
260                    let count = element.attr_number("c").unwrap_or(1).clamp(1, 64) as usize;
261                    spans.push(Span::Text(" ".repeat(count)));
262                }
263                // Frames inside a paragraph hold images, handled as blocks.
264                "frame" => {}
265                _ => collect_inline(element, styles, spans),
266            },
267        }
268    }
269}
270
271/// Images are `draw:frame` elements carrying an `svg:title`/`svg:desc`.
272fn images(paragraph: &Element) -> Vec<Block> {
273    paragraph
274        .find_all("frame")
275        .into_iter()
276        .filter(|frame| frame.find("image").is_some())
277        .map(|frame| {
278            let alt = frame
279                .find("desc")
280                .or_else(|| frame.find("title"))
281                .map(|element| element.text().trim().to_string())
282                .filter(|text| !text.is_empty())
283                .or_else(|| frame.attr("name").map(str::to_string));
284            Block::Image { alt }
285        })
286        .collect()
287}
288
289/// The style names a document refers to, resolved: character styling for spans
290/// and the bullet-versus-number choice for lists.
291#[derive(Default)]
292struct StyleTable {
293    /// Style name → (bold, italic).
294    styles: HashMap<String, (bool, bool)>,
295    /// Names of list styles whose first level is numbered.
296    ordered_lists: std::collections::HashSet<String>,
297}
298
299impl StyleTable {
300    fn parse(root: &Element) -> StyleTable {
301        let mut styles = HashMap::new();
302        let mut ordered_lists = std::collections::HashSet::new();
303
304        // `<text:list-style style:name="L1"><text:list-level-style-number …>`
305        // is a numbered list; `…-style-bullet` and `…-style-image` are not.
306        for list_style in root.find_all("list-style") {
307            let Some(name) = list_style.attr("name") else {
308                continue;
309            };
310            let numbered = list_style
311                .elements()
312                .find(|level| level.name.starts_with("list-level-style-"))
313                .is_some_and(|level| level.name == "list-level-style-number");
314            if numbered {
315                ordered_lists.insert(name.to_string());
316            }
317        }
318
319        for style in root.find_all("style") {
320            let Some(name) = style.attr("name") else {
321                continue;
322            };
323            let Some(properties) = style.child("text-properties") else {
324                continue;
325            };
326            let bold = properties.attr("font-weight").is_some_and(|weight| {
327                weight == "bold" || weight.parse().is_ok_and(|w: u32| w >= 600)
328            });
329            let italic = properties
330                .attr("font-style")
331                .is_some_and(|slant| slant == "italic" || slant == "oblique");
332
333            if bold || italic {
334                styles.insert(name.to_string(), (bold, italic));
335            }
336        }
337
338        StyleTable {
339            styles,
340            ordered_lists,
341        }
342    }
343
344    /// Bulleted unless the list's style says it counts.
345    fn is_ordered(&self, style: &str) -> bool {
346        self.ordered_lists.contains(style)
347    }
348
349    fn wrap(&self, style: &str, inner: Vec<Span>) -> Vec<Span> {
350        match self.styles.get(style) {
351            None | Some((false, false)) => inner,
352            Some((true, false)) => vec![Span::Bold(inner)],
353            Some((false, true)) => vec![Span::Italic(inner)],
354            Some((true, true)) => vec![Span::Bold(vec![Span::Italic(inner)])],
355        }
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    fn text_document(body: &str, styles: &str) -> String {
364        format!(
365            r#"<office:document-content xmlns:office="o" xmlns:text="t" xmlns:table="tb" xmlns:draw="d">
366                 <office:automatic-styles>{styles}</office:automatic-styles>
367                 <office:body><office:text>{body}</office:text></office:body>
368               </office:document-content>"#
369        )
370    }
371
372    fn blocks_of(body: &str) -> Vec<Block> {
373        parse(&text_document(body, "")).expect("valid odf")
374    }
375
376    #[test]
377    fn headings_carry_their_outline_level() {
378        assert_eq!(
379            blocks_of(
380                r#"<text:h text:outline-level="1">Report</text:h>
381                   <text:h text:outline-level="3">Detail</text:h>
382                   <text:p>Body.</text:p>"#
383            ),
384            vec![
385                Block::Heading {
386                    level: 1,
387                    text: Inline::text("Report")
388                },
389                Block::Heading {
390                    level: 3,
391                    text: Inline::text("Detail")
392                },
393                Block::paragraph("Body."),
394            ]
395        );
396    }
397
398    #[test]
399    fn spans_pick_up_styling_from_the_automatic_styles() {
400        let source = text_document(
401            r#"<text:p>plain <text:span text:style-name="T1">bold</text:span> <text:span text:style-name="T2">italic</text:span></text:p>"#,
402            r#"<style:style style:name="T1"><style:text-properties fo:font-weight="bold"/></style:style>
403               <style:style style:name="T2"><style:text-properties fo:font-style="italic"/></style:style>"#,
404        );
405        let parsed = parse(&source).unwrap();
406
407        let Block::Paragraph { text } = &parsed[0] else {
408            panic!("expected a paragraph, got {parsed:?}");
409        };
410        assert_eq!(
411            text.spans,
412            vec![
413                Span::Text("plain ".into()),
414                Span::Bold(vec![Span::Text("bold".into())]),
415                Span::Text(" ".into()),
416                Span::Italic(vec![Span::Text("italic".into())]),
417            ]
418        );
419    }
420
421    #[test]
422    fn links_tabs_and_breaks_survive() {
423        let Block::Paragraph { text } = &blocks_of(
424            r#"<text:p><text:a xlink:href="https://example.com">site</text:a><text:line-break/><text:tab/>end</text:p>"#,
425        )[0] else {
426            panic!("expected a paragraph");
427        };
428        assert_eq!(
429            text.spans,
430            vec![
431                Span::Link {
432                    href: "https://example.com".into(),
433                    text: vec![Span::Text("site".into())],
434                },
435                Span::LineBreak,
436                Span::Text("\t".into()),
437                Span::Text("end".into()),
438            ]
439        );
440    }
441
442    #[test]
443    fn nested_lists_keep_their_shape() {
444        assert_eq!(
445            blocks_of(
446                r#"<text:list>
447                     <text:list-item><text:p>one</text:p>
448                       <text:list><text:list-item><text:p>inner</text:p></text:list-item></text:list>
449                     </text:list-item>
450                     <text:list-item><text:p>two</text:p></text:list-item>
451                   </text:list>"#
452            ),
453            vec![Block::List {
454                ordered: false,
455                items: vec![
456                    vec![
457                        Block::paragraph("one"),
458                        Block::List {
459                            ordered: false,
460                            items: vec![vec![Block::paragraph("inner")]],
461                        },
462                    ],
463                    vec![Block::paragraph("two")],
464                ],
465            }]
466        );
467    }
468
469    #[test]
470    fn a_numbered_list_style_makes_an_ordered_list() {
471        let source = text_document(
472            r#"<text:list text:style-name="L1"><text:list-item><text:p>one</text:p></text:list-item></text:list>
473               <text:list text:style-name="L2"><text:list-item><text:p>two</text:p></text:list-item></text:list>"#,
474            r#"<text:list-style style:name="L1"><text:list-level-style-number text:level="1"/></text:list-style>
475               <text:list-style style:name="L2"><text:list-level-style-bullet text:level="1"/></text:list-style>"#,
476        );
477
478        let parsed = parse(&source).unwrap();
479        assert_eq!(
480            parsed,
481            vec![
482                Block::List {
483                    ordered: true,
484                    items: vec![vec![Block::paragraph("one")]],
485                },
486                Block::List {
487                    ordered: false,
488                    items: vec![vec![Block::paragraph("two")]],
489                },
490            ]
491        );
492    }
493
494    #[test]
495    fn tables_use_the_first_row_as_the_header() {
496        assert_eq!(
497            blocks_of(
498                r#"<table:table>
499                     <table:table-row><table:table-cell><text:p>a</text:p></table:table-cell><table:table-cell><text:p>b</text:p></table:table-cell></table:table-row>
500                     <table:table-row><table:table-cell><text:p>1</text:p></table:table-cell><table:table-cell><text:p>2</text:p></table:table-cell></table:table-row>
501                   </table:table>"#
502            ),
503            vec![Block::Table {
504                header: Some(Row::from_texts(["a", "b"])),
505                rows: vec![Row::from_texts(["1", "2"])],
506            }]
507        );
508    }
509
510    #[test]
511    fn images_keep_their_description() {
512        assert_eq!(
513            blocks_of(
514                r#"<text:p><draw:frame draw:name="Image1"><draw:image xlink:href="pic.png"/><svg:desc>a chart</svg:desc></draw:frame></text:p>"#
515            ),
516            vec![Block::Image {
517                alt: Some("a chart".into())
518            }]
519        );
520    }
521
522    #[test]
523    fn presentations_become_sections() {
524        let source = r#"<office:document-content xmlns:office="o" xmlns:draw="d" xmlns:text="t">
525              <office:body><office:presentation>
526                <draw:page draw:name="Intro">
527                  <draw:frame><draw:text-box><text:p>Agenda</text:p><text:p>first point</text:p></draw:text-box></draw:frame>
528                </draw:page>
529                <draw:page draw:name="Second">
530                  <draw:frame><draw:text-box><text:p>Numbers</text:p></draw:text-box></draw:frame>
531                </draw:page>
532              </office:presentation></office:body>
533            </office:document-content>"#;
534
535        assert_eq!(
536            parse(source).unwrap(),
537            vec![
538                Block::Heading {
539                    level: 2,
540                    text: Inline::text("Agenda")
541                },
542                Block::paragraph("first point"),
543                Block::PageBreak { page: 2 },
544                Block::Heading {
545                    level: 2,
546                    text: Inline::text("Numbers")
547                },
548            ]
549        );
550    }
551
552    #[test]
553    fn reads_metadata() {
554        let meta = metadata(Some(
555            r#"<office:document-meta xmlns:office="o" xmlns:dc="d" xmlns:meta="m">
556                 <office:meta>
557                   <dc:title>A title</dc:title>
558                   <dc:creator>Ada</dc:creator>
559                   <meta:creation-date>2026-07-24T10:00:00</meta:creation-date>
560                   <meta:document-statistic meta:page-count="12" meta:word-count="3400"/>
561                 </office:meta>
562               </office:document-meta>"#,
563        ));
564        assert_eq!(meta.title.as_deref(), Some("A title"));
565        assert_eq!(meta.author.as_deref(), Some("Ada"));
566        assert_eq!(meta.created.as_deref(), Some("2026-07-24T10:00:00"));
567        assert_eq!(meta.page_count, Some(12));
568        assert_eq!(metadata(None), Metadata::default());
569    }
570
571    #[test]
572    fn content_without_a_body_is_not_an_error() {
573        assert!(
574            parse(r#"<office:document-content xmlns:office="o"/>"#)
575                .unwrap()
576                .is_empty()
577        );
578    }
579}