Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
refactor(api): rewrite doc/docx/odt/rtf providers (#4174)
tomsideguide7d6eb8d9bb92
diff --git a/apps/api/native/Cargo.toml b/apps/api/native/Cargo.tomlindex f35e92f4e..4fbe8afb0 100644--- a/apps/api/native/Cargo.toml+++ b/apps/api/native/Cargo.toml@@ -28,6 +28,8 @@ url = "2.5.7"zip = "5.0.0"calamine = { git = "https://github.com/firecrawl/calamine", branch = "fc-prod" }cfb = "0.10"+codepage = "0.1"+encoding_rs = "0.8"tokio = "1.48.0"tracing = "0.1"tracing-subscriber = { version = "0.3", default-features = false, features = ["registry"] }diff --git a/apps/api/native/src/document/encoding.rs b/apps/api/native/src/document/encoding.rsnew file mode 100644index 000000000..858c0cb73--- /dev/null+++ b/apps/api/native/src/document/encoding.rs@@ -0,0 +1,38 @@+use encoding_rs::{Encoding, WINDOWS_1252};++/// Encoding for a Windows code page. Rejects the Unicode pseudo code pages,+/// which never describe single-byte legacy text.+pub fn encoding_for_codepage(codepage: u16) -> Option<&'static Encoding> {+ match codepage {+ 0 | 1200 | 1201 | 65000 | 65001 => None,+ cp => codepage::to_encoding(cp),+ }+}++/// Default ANSI code page encoding for a Windows language ID.+pub fn encoding_for_lid(lid: u16) -> &'static Encoding {+ let codepage = match lid {+ // sublanguage decides the script for these+ 0x0404 | 0x0C04 | 0x1404 | 0x7C04 => 950, // Chinese (Taiwan, Hong Kong, Macau, Traditional)+ 0x0C1A | 0x1C1A => 1251, // Serbian (Cyrillic)+ 0x082C | 0x0843 => 1251, // Azerbaijani, Uzbek (Cyrillic)+ _ => match lid & 0x3FF {+ 0x04 => 936, // Chinese (Simplified unless a Traditional sublanguage above)+ // Central European+ 0x05 | 0x0E | 0x15 | 0x18 | 0x1A | 0x1B | 0x1C | 0x24 => 1250,+ // Cyrillic+ 0x02 | 0x19 | 0x22 | 0x23 | 0x2F | 0x3F | 0x40 | 0x44 | 0x50 => 1251,+ 0x08 => 1253, // Greek+ 0x1F | 0x2C | 0x43 => 1254, // Turkish, Azerbaijani, Uzbek (Latin)+ 0x0D => 1255, // Hebrew+ 0x01 | 0x20 | 0x29 => 1256, // Arabic, Urdu, Persian+ 0x25 | 0x26 | 0x27 => 1257, // Baltic+ 0x2A => 1258, // Vietnamese+ 0x1E => 874, // Thai+ 0x11 => 932, // Japanese+ 0x12 => 949, // Korean+ _ => 1252,+ },+ };+ encoding_for_codepage(codepage).unwrap_or(WINDOWS_1252)+}diff --git a/apps/api/native/src/document/mod.rs b/apps/api/native/src/document/mod.rsindex 7c0ff9030..278c8c3c4 100644--- a/apps/api/native/src/document/mod.rs+++ b/apps/api/native/src/document/mod.rs@@ -1,6 +1,9 @@+pub mod encoding;pub mod model;+pub mod oleps;pub mod providers;pub mod renderers;+pub mod xml;pub use providers::factory::DocumentType;diff --git a/apps/api/native/src/document/model/mod.rs b/apps/api/native/src/document/model/mod.rsindex 2c9777455..444acb88e 100644--- a/apps/api/native/src/document/model/mod.rs+++ b/apps/api/native/src/document/model/mod.rs@@ -65,6 +65,21 @@ pub enum Inline {Bookmark(BookmarkId),}+/// True when the inlines would render something the reader can see.+pub fn has_visible_content(inlines: &[Inline]) -> bool {+ inlines.iter().any(|inline| match inline {+ Inline::Text(t) => !t.trim().is_empty(),+ Inline::LineBreak => false,+ Inline::Link { children, .. } => has_visible_content(children),+ Inline::Strong(c) | Inline::Em(c) | Inline::Del(c) | Inline::Sup(c) | Inline::Sub(c) => {+ has_visible_content(c)+ }+ Inline::Code(t) => !t.trim().is_empty(),+ Inline::FootnoteRef(_) | Inline::EndnoteRef(_) | Inline::CommentRef(_) => true,+ Inline::Bookmark(_) => false,+ })+}+#[derive(Debug, Clone)]pub struct Image {pub src: String,diff --git a/apps/api/native/src/document/oleps.rs b/apps/api/native/src/document/oleps.rsnew file mode 100644index 000000000..7c2f09ce3--- /dev/null+++ b/apps/api/native/src/document/oleps.rs@@ -0,0 +1,136 @@+//! Minimal MS-OLEPS parser for the `\x05SummaryInformation` stream of OLE+//! compound files.++use crate::document::encoding::encoding_for_codepage;+use chrono::{DateTime, Utc};+use encoding_rs::WINDOWS_1252;++const PID_CODEPAGE: u32 = 0x0001;+const PIDSI_TITLE: u32 = 0x0002;+const PIDSI_AUTHOR: u32 = 0x0004;+const PIDSI_CREATE_DTM: u32 = 0x000C;++const VT_I2: u32 = 0x0002;+const VT_LPSTR: u32 = 0x001E;+const VT_LPWSTR: u32 = 0x001F;+const VT_FILETIME: u32 = 0x0040;++/// Seconds between the FILETIME epoch (1601) and the Unix epoch (1970).+const FILETIME_UNIX_EPOCH_DIFF_SECS: i64 = 11_644_473_600;++#[derive(Debug, Default)]+pub struct SummaryInformation {+ pub codepage: Option<u16>,+ pub title: Option<String>,+ pub author: Option<String>,+ pub created: Option<DateTime<Utc>>,+}++pub fn parse_summary_information(data: &[u8]) -> Option<SummaryInformation> {+ // byte order mark at 0, property set count at 0x18, first section offset at 0x2C+ if read_u16(data, 0)? != 0xFFFE {+ return None;+ }+ if read_u32(data, 0x18)? == 0 {+ return None;+ }+ let section_start = read_u32(data, 0x2C)? as usize;++ let num_properties = (read_u32(data, section_start + 4)? as usize).min(1024);+ let mut properties = Vec::with_capacity(num_properties);+ for i in 0..num_properties {+ let entry = section_start + 8 + i * 8;+ let prop_id = read_u32(data, entry)?;+ let prop_offset = section_start + read_u32(data, entry + 4)? as usize;+ properties.push((prop_id, prop_offset));+ }++ let mut info = SummaryInformation::default();++ // code page first, it governs VT_LPSTR decoding+ info.codepage = properties+ .iter()+ .find(|(id, _)| *id == PID_CODEPAGE)+ .and_then(|(_, offset)| {+ if read_u32(data, *offset)? != VT_I2 {+ return None;+ }+ read_u16(data, offset + 4)+ });+ let string_encoding = info+ .codepage+ .and_then(encoding_for_codepage)+ .unwrap_or(WINDOWS_1252);++ for (prop_id, offset) in properties {+ match prop_id {+ PIDSI_TITLE => info.title = read_string(data, offset, string_encoding),+ PIDSI_AUTHOR => info.author = read_string(data, offset, string_encoding),+ PIDSI_CREATE_DTM => info.created = read_filetime(data, offset),+ _ => {}+ }+ }++ Some(info)+}++fn read_string(+ data: &[u8],+ offset: usize,+ encoding: &'static encoding_rs::Encoding,+) -> Option<String> {+ let vt = read_u32(data, offset)?;+ let len = read_u32(data, offset + 4)? as usize;+ let text = match vt {+ VT_LPSTR => {+ let bytes = data.get(offset + 8..offset + 8 + len)?;+ let (decoded, _, _) = encoding.decode(bytes);+ decoded.into_owned()+ }+ VT_LPWSTR => {+ let bytes = data.get(offset + 8..offset + 8 + len.checked_mul(2)?)?;+ let units: Vec<u16> = bytes+ .chunks_exact(2)+ .map(|c| u16::from_le_bytes([c[0], c[1]]))+ .collect();+ String::from_utf16_lossy(&units)+ }+ _ => return None,+ };+ let text = text.trim_end_matches('\0').trim();+ if text.is_empty() {+ None+ } else {+ Some(text.to_string())+ }+}++fn read_filetime(data: &[u8], offset: usize) -> Option<DateTime<Utc>> {+ if read_u32(data, offset)? != VT_FILETIME {+ return None;+ }+ let filetime = read_u64(data, offset + 4)?;+ if filetime == 0 {+ return None;+ }+ let secs = (filetime / 10_000_000) as i64 - FILETIME_UNIX_EPOCH_DIFF_SECS;+ let nanos = (filetime % 10_000_000) as u32 * 100;+ DateTime::from_timestamp(secs, nanos)+}++fn read_u16(data: &[u8], offset: usize) -> Option<u16> {+ let bytes = data.get(offset..offset + 2)?;+ Some(u16::from_le_bytes([bytes[0], bytes[1]]))+}++fn read_u32(data: &[u8], offset: usize) -> Option<u32> {+ let bytes = data.get(offset..offset + 4)?;+ Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))+}++fn read_u64(data: &[u8], offset: usize) -> Option<u64> {+ let bytes = data.get(offset..offset + 8)?;+ Some(u64::from_le_bytes([+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],+ ]))+}diff --git a/apps/api/native/src/document/providers/doc.rs b/apps/api/native/src/document/providers/doc.rsindex 1c94b656b..04c7b2311 100644--- a/apps/api/native/src/document/providers/doc.rs+++ b/apps/api/native/src/document/providers/doc.rs@@ -1,9 +1,21 @@+//! Legacy Word binary (.doc) provider, following the MS-DOC piece table+//! format.++use crate::document::encoding::{encoding_for_codepage, encoding_for_lid};use crate::document::model::*;+use crate::document::oleps::parse_summary_information;use crate::document::providers::DocumentProvider;use cfb::CompoundFile;+use encoding_rs::Encoding;use std::error::Error;-use std::io::Cursor;-use std::io::Read;+use std::io::{Cursor, Read, Seek};++const MAGIC_WORD_97: u16 = 0xA5EC;+const MAGIC_WORD_6_95: u16 = 0xA5DC;++/// Caps text extraction so a malformed piece table cannot force+/// multi-gigabyte output from a small file.+const MAX_TEXT_CHARS: usize = 10_000_000;pub struct DocProvider;@@ -15,25 +27,41 @@ impl DocProvider {impl DocumentProvider for DocProvider {fn parse_buffer(&self, data: &[u8]) -> Result<Document, Box<dyn Error + Send + Sync>> {- let cursor = Cursor::new(data);- let mut cfb = CompoundFile::open(cursor)?;+ let mut cfb = CompoundFile::open(Cursor::new(data))?;- let mut metadata = DocumentMetadata::default();+ let summary = read_stream(&mut cfb, "\x05SummaryInformation")+ .ok()+ .and_then(|bytes| parse_summary_information(&bytes));- // Try to extract metadata from SummaryInformation stream- if let Ok(summary_info) = extract_summary_info(&mut cfb) {- metadata.title = summary_info.title;- metadata.author = summary_info.author;- }+ let word_doc = read_stream(&mut cfb, "WordDocument")?;+ let fib = Fib::parse(&word_doc)?;- // Extract text content from the document- let text_content = extract_text_content(&mut cfb)?;+ let (primary, secondary) = if fib.table_stream_1 {+ ("1Table", "0Table")+ } else {+ ("0Table", "1Table")+ };+ let table = read_stream(&mut cfb, primary)+ .or_else(|_| read_stream(&mut cfb, secondary))+ .ok();++ let ansi = summary+ .as_ref()+ .and_then(|s| s.codepage)+ .and_then(encoding_for_codepage)+ .unwrap_or_else(|| encoding_for_lid(fib.lid));- // Convert the extracted text to document blocks- let blocks = text_to_blocks(&text_content);+ let text = extract_text(&word_doc, table.as_deref(), &fib, ansi);++ let mut metadata = DocumentMetadata::default();+ if let Some(summary) = summary {+ metadata.title = summary.title;+ metadata.author = summary.author;+ metadata.created = summary.created;+ }Ok(Document {- blocks,+ blocks: text_to_blocks(&text),metadata,notes: Vec::new(),comments: Vec::new(),@@ -45,376 +73,587 @@ impl DocumentProvider for DocProvider {}}-#[derive(Default)]-struct SummaryInfo {- title: Option<String>,- author: Option<String>,-}--fn extract_summary_info<R: Read + std::io::Seek>(+fn read_stream<R: Read + Seek>(cfb: &mut CompoundFile<R>,-) -> Result<SummaryInfo, Box<dyn Error + Send + Sync>> {- let mut info = SummaryInfo::default();-- // Try to read the SummaryInformation stream- if let Ok(mut stream) = cfb.open_stream("\x05SummaryInformation") {- let mut buf = Vec::new();- stream.read_to_end(&mut buf)?;-- // Parse the OLE property set stream to extract title and author- if let Some((title, author)) = parse_summary_info_stream(&buf) {- info.title = title;- info.author = author;- }- }-- Ok(info)+ name: &str,+) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>> {+ let mut stream = cfb.open_stream(name)?;+ let mut buf = Vec::new();+ stream.read_to_end(&mut buf)?;+ Ok(buf)}-fn parse_summary_info_stream(data: &[u8]) -> Option<(Option<String>, Option<String>)> {- // MS-OLEPS: Property Set Stream format- // This is a simplified parser that extracts strings from the property stream-- if data.len() < 48 {- return None;- }-- // Byte order mark at offset 0 should be 0xFFFE (little-endian)- if data.len() >= 2 && (data[0] != 0xFE || data[1] != 0xFF) {- return None;- }-- let mut title: Option<String> = None;- let mut author: Option<String> = None;+struct Fib {+ legacy: bool,+ lid: u16,+ table_stream_1: bool,+ ext_char: bool,+ fc_min: usize,+ fc_mac: usize,+ ccp_text: usize,+ fc_clx: usize,+ lcb_clx: usize,+}- // Extract readable strings from the property stream- let strings = extract_ascii_strings(data, 3);+impl Fib {+ fn parse(word_doc: &[u8]) -> Result<Self, Box<dyn Error + Send + Sync>> {+ if word_doc.len() < 0x20 {+ return Err("WordDocument stream too short".into());+ }+ let magic = read_u16(word_doc, 0x00);+ let legacy = match magic {+ MAGIC_WORD_97 => false,+ MAGIC_WORD_6_95 => true,+ _ => return Err(format!("not a Word document (magic {magic:#06X})").into()),+ };++ let flags = read_u16(word_doc, 0x0A);+ if flags & 0x0100 != 0 {+ return Err("encrypted .doc files are not supported".into());+ }- // Filter out common non-title/author strings- let filtered: Vec<&str> = strings- .iter()- .map(|s| s.as_str())- .filter(|s| {- !s.contains("Microsoft")- && !s.contains("Normal")- && !s.contains("template")- && !s.starts_with("http")- && s.len() >= 2- && s.len() <= 200+ Ok(Fib {+ legacy,+ lid: read_u16(word_doc, 0x06),+ table_stream_1: flags & 0x0200 != 0,+ ext_char: flags & 0x1000 != 0,+ fc_min: read_u32(word_doc, 0x18) as usize,+ fc_mac: read_u32(word_doc, 0x1C) as usize,+ ccp_text: if word_doc.len() >= 0x50 {+ read_u32(word_doc, 0x4C) as usize+ } else {+ 0+ },+ fc_clx: if word_doc.len() >= 0x1AA {+ read_u32(word_doc, 0x1A2) as usize+ } else {+ 0+ },+ lcb_clx: if word_doc.len() >= 0x1AA {+ read_u32(word_doc, 0x1A6) as usize+ } else {+ 0+ },})- .collect();-- // Title and author are typically the first meaningful strings- if let Some(t) = filtered.first() {- title = Some(t.to_string());- }- if let Some(a) = filtered.get(1) {- author = Some(a.to_string());}-- Some((title, author))}-fn extract_text_content<R: Read + std::io::Seek>(- cfb: &mut CompoundFile<R>,-) -> Result<String, Box<dyn Error + Send + Sync>> {- // Try to read the WordDocument stream- if let Ok(mut stream) = cfb.open_stream("WordDocument") {- let mut doc_data = Vec::new();- stream.read_to_end(&mut doc_data)?;-- // Extract text from the WordDocument stream- if let Some(text) = extract_text_from_word_document(&doc_data) {- if !text.trim().is_empty() {- return Ok(text);+fn extract_text(+ word_doc: &[u8],+ table: Option<&[u8]>,+ fib: &Fib,+ ansi: &'static Encoding,+) -> String {+ if !fib.legacy {+ if let Some(table) = table {+ if let Some(pieces) = parse_piece_table(table, fib) {+ return decode_pieces(word_doc, &pieces, fib.ccp_text, ansi);}}}- // Fallback: scan all streams for text- extract_text_fallback(cfb)+ // Word 6/95 files and corrupt piece tables: text is at fcMin..fcMac.+ let start = fib.fc_min.min(word_doc.len());+ let end = fib.fc_mac.clamp(start, word_doc.len());+ let bytes = &word_doc[start..end];+ if fib.ext_char {+ decode_utf16le(bytes)+ } else {+ ansi.decode_without_bom_handling(bytes).0.into_owned()+ }}-fn extract_text_from_word_document(doc_data: &[u8]) -> Option<String> {- if doc_data.len() < 32 {- return None;- }+struct Piece {+ start_cp: u32,+ end_cp: u32,+ offset: usize,+ compressed: bool,+}- // Check for Word magic number (0xA5EC for Word 97-2003, 0xA5DC for older)- let magic = u16::from_le_bytes([doc_data[0], doc_data[1]]);- if magic != 0xA5EC && magic != 0xA5DC {+fn parse_piece_table(table: &[u8], fib: &Fib) -> Option<Vec<Piece>> {+ if fib.lcb_clx == 0 {return None;}+ let clx = table.get(fib.fc_clx..fib.fc_clx.checked_add(fib.lcb_clx)?)?;- // Read the FIB (File Information Block) to get text encoding info- // Bit 9 of flags (offset 0x0A) indicates which table stream to use- // But for text extraction, we'll use a more robust approach-- // The FIB contains ccpText at offset 0x4C (character count of main text)- let ccp_text = if doc_data.len() > 0x50 {- u32::from_le_bytes([- doc_data[0x4C],- doc_data[0x4D],- doc_data[0x4E],- doc_data[0x4F],- ]) as usize- } else {- 0- };-- // For complex documents, text may be in pieces. For simple ones, it's contiguous.- // Either way, we'll scan for text runs since the piece table parsing is complex.-- // .doc files typically store text as CP1252 (single-byte) or UTF-16LE- // We'll try to detect which one by looking for patterns-- // First, try to find substantial ASCII/CP1252 text runs- let ascii_text = extract_document_text_cp1252(doc_data, ccp_text);- if !ascii_text.trim().is_empty() && has_enough_words(&ascii_text, 10) {- return Some(ascii_text);+ // Clx: zero or more Prc (0x01) blocks, then the Pcdt (0x02) piece table.+ let mut i = 0;+ while i < clx.len() {+ match clx[i] {+ 0x01 => {+ let cb = read_u16(clx.get(i + 1..i + 3)?, 0) as usize;+ i += 3 + cb;+ }+ 0x02 => {+ let lcb = read_u32(clx.get(i + 1..i + 5)?, 0) as usize;+ let plc = clx.get(i + 5..(i + 5).checked_add(lcb)?)?;+ return parse_plc_pcd(plc);+ }+ _ => return None,+ }}+ None+}- // If ASCII extraction didn't work well, try UTF-16LE- let utf16_text = extract_document_text_utf16(doc_data, ccp_text);- if !utf16_text.trim().is_empty() && has_enough_words(&utf16_text, 10) {- return Some(utf16_text);+fn parse_plc_pcd(plc: &[u8]) -> Option<Vec<Piece>> {+ // n+1 CPs (4 bytes each) followed by n PCDs (8 bytes each)+ if plc.len() < 16 || (plc.len() - 4) % 12 != 0 {+ return None;+ }+ let n = (plc.len() - 4) / 12;++ let mut pieces = Vec::with_capacity(n);+ for k in 0..n {+ let start_cp = read_u32(plc, k * 4);+ let end_cp = read_u32(plc, (k + 1) * 4);+ if end_cp < start_cp {+ return None;+ }+ let fc = read_u32(plc, 4 * (n + 1) + 8 * k + 2);+ let compressed = fc & 0x4000_0000 != 0;+ let offset = if compressed {+ ((fc & 0x3FFF_FFFF) / 2) as usize+ } else {+ (fc & 0x3FFF_FFFF) as usize+ };+ pieces.push(Piece {+ start_cp,+ end_cp,+ offset,+ compressed,+ });}+ Some(pieces)+}- // Return whichever has more content- if ascii_text.len() > utf16_text.len() {- Some(ascii_text)- } else if !utf16_text.is_empty() {- Some(utf16_text)- } else {- None+fn decode_pieces(+ word_doc: &[u8],+ pieces: &[Piece],+ ccp_text: usize,+ ansi: &'static Encoding,+) -> String {+ // piece CP ranges are contiguous and ascending, so clamping ccpText bounds+ // the total output no matter how many pieces the table declares+ let ccp_text = ccp_text.min(MAX_TEXT_CHARS);+ let mut out = String::new();+ for piece in pieces {+ // main document body only; headers, footnotes etc. live past ccpText+ if piece.start_cp as usize >= ccp_text {+ continue;+ }+ let count = (piece.end_cp as usize).min(ccp_text) - piece.start_cp as usize;+ let available = word_doc.len().saturating_sub(piece.offset);+ if piece.compressed {+ let bytes = &word_doc[piece.offset.min(word_doc.len())..][..count.min(available)];+ out.push_str(&ansi.decode_without_bom_handling(bytes).0);+ } else {+ let bytes = &word_doc[piece.offset.min(word_doc.len())..][..(count * 2).min(available)];+ out.push_str(&decode_utf16le(bytes));+ }}+ out}-fn extract_document_text_cp1252(data: &[u8], expected_chars: usize) -> String {- // Find long runs of printable ASCII/CP1252 characters- // This works well for most .doc files where text is stored as single-byte- let mut text_runs: Vec<String> = Vec::new();- let mut current_run = String::new();- let mut total_chars = 0;- let max_chars = if expected_chars > 0 && expected_chars < 10_000_000 {- expected_chars * 2 // Allow some extra for headers/footers- } else {- 10_000_000- };+fn decode_utf16le(bytes: &[u8]) -> String {+ let units: Vec<u16> = bytes+ .chunks_exact(2)+ .map(|c| u16::from_le_bytes([c[0], c[1]]))+ .collect();+ String::from_utf16_lossy(&units)+}- for &byte in data.iter() {- if total_chars >= max_chars {- break;+fn text_to_blocks(text: &str) -> Vec<Block> {+ let mut blocks = Vec::new();+ let mut inlines: Vec<Inline> = Vec::new();+ let mut buf = String::new();+ // per-field flag: true while inside the instruction part (before 0x14)+ let mut field_stack: Vec<bool> = Vec::new();++ fn flush_text(buf: &mut String, inlines: &mut Vec<Inline>) {+ if !buf.is_empty() {+ inlines.push(Inline::Text(std::mem::take(buf)));}+ }- let ch = decode_cp1252(byte);-- if is_text_char(ch) {- current_run.push(ch);- } else if byte == 0x0D || byte == 0x0A {- // Carriage return or line feed - end of paragraph- if current_run.len() >= 20 && has_word_chars(¤t_run) {- text_runs.push(current_run.clone());- total_chars += current_run.len();+ fn flush_paragraph(buf: &mut String, inlines: &mut Vec<Inline>, blocks: &mut Vec<Block>) {+ flush_text(buf, inlines);+ while matches!(inlines.last(), Some(Inline::LineBreak)) {+ inlines.pop();+ }+ if has_visible_content(inlines) {+ if let Some(Inline::Text(first)) = inlines.first_mut() {+ *first = first.trim_start().to_string();}- current_run.clear();- } else if byte == 0x09 {- // Tab- current_run.push('\t');- } else {- // Non-text byte - might be end of a text run- if current_run.len() >= 20 && has_word_chars(¤t_run) {- text_runs.push(current_run.clone());- total_chars += current_run.len();+ if let Some(Inline::Text(last)) = inlines.last_mut() {+ *last = last.trim_end().to_string();}- current_run.clear();+ blocks.push(Block::Paragraph(Paragraph {+ kind: ParagraphKind::Normal,+ inlines: std::mem::take(inlines),+ }));+ } else {+ inlines.clear();}}- // Don't forget the last run- if current_run.len() >= 20 && has_word_chars(¤t_run) {- text_runs.push(current_run);- }-- // Join text runs with newlines- text_runs.join("\n")-}--fn extract_document_text_utf16(data: &[u8], expected_chars: usize) -> String {- let mut text = String::new();- let max_chars = if expected_chars > 0 && expected_chars < 10_000_000 {- expected_chars * 2- } else {- 10_000_000- };-- let mut i = 0;- let mut char_count = 0;- while i + 1 < data.len() && char_count < max_chars {- let code = u16::from_le_bytes([data[i], data[i + 1]]);-- if let Some(ch) = char::from_u32(code as u32) {- if is_text_char(ch) || ch == '\r' || ch == '\n' || ch == '\t' {- if ch == '\r' {- text.push('\n');- } else {- text.push(ch);+ for ch in text.chars() {+ match ch {+ '\u{13}' => {+ field_stack.push(true);+ continue;+ }+ '\u{14}' => {+ if let Some(top) = field_stack.last_mut() {+ *top = false;}- char_count += 1;+ continue;+ }+ '\u{15}' => {+ field_stack.pop();+ continue;}+ _ => {}+ }+ if field_stack.iter().any(|&in_instruction| in_instruction) {+ continue;+ }+ match ch {+ // paragraph mark, cell/row mark, page break, column break+ '\r' | '\n' | '\u{7}' | '\u{c}' | '\u{e}' => {+ flush_paragraph(&mut buf, &mut inlines, &mut blocks)+ }+ '\u{b}' => {+ flush_text(&mut buf, &mut inlines);+ if !inlines.is_empty() {+ inlines.push(Inline::LineBreak);+ }+ }+ '\t' => buf.push('\t'),+ '\u{1e}' => buf.push('-'),+ c if c.is_control() || c == '\u{1f}' => {}+ c => buf.push(c),}- i += 2;}+ flush_paragraph(&mut buf, &mut inlines, &mut blocks);- // Filter to only keep substantial text portions- let lines: Vec<&str> = text- .lines()- .filter(|line| line.len() >= 10 && has_word_chars(line))- .collect();-- lines.join("\n")+ blocks}-fn has_word_chars(s: &str) -> bool {- // Check if the string contains actual word characters (letters)- let letter_count = s.chars().filter(|c| c.is_alphabetic()).count();- let total_count = s.chars().count();- // At least 30% should be letters- letter_count > 0 && (letter_count * 100 / total_count.max(1)) >= 30+fn read_u16(data: &[u8], offset: usize) -> u16 {+ u16::from_le_bytes([data[offset], data[offset + 1]])}-fn has_enough_words(s: &str, min_words: usize) -> bool {- s.split_whitespace().count() >= min_words+fn read_u32(data: &[u8], offset: usize) -> u32 {+ u32::from_le_bytes([+ data[offset],+ data[offset + 1],+ data[offset + 2],+ data[offset + 3],+ ])}-fn is_text_char(ch: char) -> bool {- // Printable character (not control chars, but allow some special ones)- (ch >= ' ' && ch != '\x7F') || ch == '\t'-}+#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;-fn extract_ascii_strings(data: &[u8], min_length: usize) -> Vec<String> {- let mut strings = Vec::new();- let mut current = String::new();+ enum TestPiece {+ Compressed(Vec<u8>),+ Unicode(&'static str),+ }- for &byte in data {- let ch = decode_cp1252(byte);- if ch.is_ascii_graphic() || ch == ' ' {- current.push(ch);- } else {- if current.len() >= min_length {- strings.push(current.clone());- }- current.clear();- }+ fn utf16_bytes(text: &str) -> Vec<u8> {+ text.encode_utf16().flat_map(u16::to_le_bytes).collect()}- if current.len() >= min_length {- strings.push(current);+ const TEXT_START: usize = 0x200;++ fn build_word_doc_streams(pieces: &[TestPiece], lid: u16) -> (Vec<u8>, Vec<u8>) {+ let mut word_doc = vec![0u8; TEXT_START];+ let mut cps = vec![0u32];+ let mut pcds = Vec::new();++ for piece in pieces {+ let offset = word_doc.len();+ let (count, fc) = match piece {+ TestPiece::Compressed(bytes) => {+ word_doc.extend_from_slice(bytes);+ (bytes.len() as u32, (offset as u32 * 2) | 0x4000_0000)+ }+ TestPiece::Unicode(text) => {+ let bytes = utf16_bytes(text);+ word_doc.extend_from_slice(&bytes);+ (text.encode_utf16().count() as u32, offset as u32)+ }+ };+ cps.push(cps.last().unwrap() + count);+ pcds.push(fc);+ }++ let ccp_text = *cps.last().unwrap();+ let mut plc = Vec::new();+ for cp in &cps {+ plc.extend_from_slice(&cp.to_le_bytes());+ }+ for fc in &pcds {+ plc.extend_from_slice(&0u16.to_le_bytes());+ plc.extend_from_slice(&fc.to_le_bytes());+ plc.extend_from_slice(&0u16.to_le_bytes());+ }+ let mut table = vec![0x02];+ table.extend_from_slice(&(plc.len() as u32).to_le_bytes());+ table.extend_from_slice(&plc);++ word_doc[0x00..0x02].copy_from_slice(&MAGIC_WORD_97.to_le_bytes());+ word_doc[0x02..0x04].copy_from_slice(&0x00C1u16.to_le_bytes());+ word_doc[0x06..0x08].copy_from_slice(&lid.to_le_bytes());+ word_doc[0x0A..0x0C].copy_from_slice(&0x0200u16.to_le_bytes());+ word_doc[0x4C..0x50].copy_from_slice(&ccp_text.to_le_bytes());+ word_doc[0x1A2..0x1A6].copy_from_slice(&0u32.to_le_bytes());+ word_doc[0x1A6..0x1AA].copy_from_slice(&(table.len() as u32).to_le_bytes());++ (word_doc, table)}- strings-}+ fn build_cfb(streams: &[(&str, &[u8])]) -> Vec<u8> {+ let mut comp = CompoundFile::create(Cursor::new(Vec::new())).unwrap();+ for (name, data) in streams {+ let mut stream = comp.create_stream(name).unwrap();+ stream.write_all(data).unwrap();+ }+ comp.into_inner().into_inner()+ }-fn extract_text_fallback<R: Read + std::io::Seek>(- cfb: &mut CompoundFile<R>,-) -> Result<String, Box<dyn Error + Send + Sync>> {- let mut all_text = String::new();-- // List all streams and try to extract text from each- let entries: Vec<String> = cfb- .walk()- .filter(|e| e.is_stream())- .map(|e| e.path().to_string_lossy().to_string())- .collect();+ fn build_doc(pieces: &[TestPiece], lid: u16, summary: Option<&[u8]>) -> Vec<u8> {+ let (word_doc, table) = build_word_doc_streams(pieces, lid);+ let mut streams: Vec<(&str, &[u8])> = vec![("WordDocument", &word_doc), ("1Table", &table)];+ if let Some(summary) = summary {+ streams.push(("\x05SummaryInformation", summary));+ }+ build_cfb(&streams)+ }- for entry in entries {- // Skip known non-text streams- if entry.contains("CompObj")- || entry.contains("Data")- || entry.contains("ObjectPool")- || entry.contains("Pictures")- {- continue;+ fn build_summary_information(codepage: u16, title: &[u8], author: &[u8]) -> Vec<u8> {+ let mut props: Vec<(u32, Vec<u8>)> = Vec::new();+ let mut codepage_value = 0x0002u32.to_le_bytes().to_vec();+ codepage_value.extend_from_slice(&(codepage as u32).to_le_bytes());+ props.push((0x0001, codepage_value));+ for (pid, text) in [(0x0002u32, title), (0x0004u32, author)] {+ let mut value = 0x001Eu32.to_le_bytes().to_vec();+ value.extend_from_slice(&((text.len() + 1) as u32).to_le_bytes());+ value.extend_from_slice(text);+ value.push(0);+ props.push((pid, value));}- if let Ok(mut stream) = cfb.open_stream(&entry) {- let mut buf = Vec::new();- if stream.read_to_end(&mut buf).is_ok() {- let stream_text = extract_document_text_cp1252(&buf, 0);- if !stream_text.trim().is_empty() && has_enough_words(&stream_text, 5) {- if !all_text.is_empty() {- all_text.push('\n');- }- all_text.push_str(&stream_text);- }+ let section_start = 0x30usize;+ let header_size = 8 + props.len() * 8;+ let mut entries = Vec::new();+ let mut values = Vec::new();+ for (pid, value) in &props {+ entries.extend_from_slice(&pid.to_le_bytes());+ entries.extend_from_slice(&((header_size + values.len()) as u32).to_le_bytes());+ values.extend_from_slice(value);+ while values.len() % 4 != 0 {+ values.push(0);}}++ let mut data = vec![0u8; section_start];+ data[0x00..0x02].copy_from_slice(&0xFFFEu16.to_le_bytes());+ data[0x18..0x1C].copy_from_slice(&1u32.to_le_bytes());+ data[0x2C..0x30].copy_from_slice(&(section_start as u32).to_le_bytes());+ data.extend_from_slice(&((header_size + values.len()) as u32).to_le_bytes());+ data.extend_from_slice(&(props.len() as u32).to_le_bytes());+ data.extend_from_slice(&entries);+ data.extend_from_slice(&values);+ data}- Ok(all_text)-}+ fn paragraph_texts(document: &Document) -> Vec<String> {+ document+ .blocks+ .iter()+ .map(|block| match block {+ Block::Paragraph(p) => p+ .inlines+ .iter()+ .map(|inline| match inline {+ Inline::Text(t) => t.as_str(),+ Inline::LineBreak => "\n",+ _ => "",+ })+ .collect::<String>(),+ _ => String::new(),+ })+ .collect()+ }-fn decode_cp1252(b: u8) -> char {- if b < 0x80 {- return b as char;- }- match b {- 0x80 => '\u{20AC}', // Euro sign- 0x82 => '\u{201A}', // Single low-9 quotation mark- 0x83 => '\u{0192}', // Latin small letter f with hook- 0x84 => '\u{201E}', // Double low-9 quotation mark- 0x85 => '\u{2026}', // Horizontal ellipsis- 0x86 => '\u{2020}', // Dagger- 0x87 => '\u{2021}', // Double dagger- 0x88 => '\u{02C6}', // Modifier letter circumflex accent- 0x89 => '\u{2030}', // Per mille sign- 0x8A => '\u{0160}', // Latin capital letter S with caron- 0x8B => '\u{2039}', // Single left-pointing angle quotation mark- 0x8C => '\u{0152}', // Latin capital ligature OE- 0x8E => '\u{017D}', // Latin capital letter Z with caron- 0x91 => '\u{2018}', // Left single quotation mark- 0x92 => '\u{2019}', // Right single quotation mark- 0x93 => '\u{201C}', // Left double quotation mark- 0x94 => '\u{201D}', // Right double quotation mark- 0x95 => '\u{2022}', // Bullet- 0x96 => '\u{2013}', // En dash- 0x97 => '\u{2014}', // Em dash- 0x98 => '\u{02DC}', // Small tilde- 0x99 => '\u{2122}', // Trade mark sign- 0x9A => '\u{0161}', // Latin small letter s with caron- 0x9B => '\u{203A}', // Single right-pointing angle quotation mark- 0x9C => '\u{0153}', // Latin small ligature oe- 0x9E => '\u{017E}', // Latin small letter z with caron- 0x9F => '\u{0178}', // Latin capital letter Y with diaeresis- _ => char::from_u32(b as u32).unwrap_or('?'),+ fn parse(data: &[u8]) -> Document {+ DocProvider::new().parse_buffer(data).unwrap()}-}-fn text_to_blocks(text: &str) -> Vec<Block> {- let mut blocks = Vec::new();+ fn cp1251(text: &str) -> Vec<u8> {+ encoding_rs::WINDOWS_1251.encode(text).0.into_owned()+ }- // Split text into paragraphs and create blocks- for paragraph in text.split('\n') {- let trimmed = paragraph.trim();- if trimmed.is_empty() {- continue;- }+ #[test]+ fn unicode_pieces() {+ let data = build_doc(+ &[TestPiece::Unicode("Указ Президента України\rДодаток\r")],+ 0x0409,+ None,+ );+ assert_eq!(+ paragraph_texts(&parse(&data)),+ vec!["Указ Президента України", "Додаток"]+ );+ }- // Clean up the text - remove control characters except tabs- let cleaned: String = trimmed- .chars()- .filter(|c| !c.is_control() || *c == '\t')- .collect();+ #[test]+ fn compressed_cp1251_via_summary_codepage() {+ let summary = build_summary_information(1251, &cp1251("Указ"), &cp1251("Автор"));+ let data = build_doc(+ &[TestPiece::Compressed(cp1251("ПРЕЗИДЕНТ УКРАЇНИ\r"))],+ 0x0409,+ Some(&summary),+ );+ let document = parse(&data);+ assert_eq!(paragraph_texts(&document), vec!["ПРЕЗИДЕНТ УКРАЇНИ"]);+ assert_eq!(document.metadata.title.as_deref(), Some("Указ"));+ assert_eq!(document.metadata.author.as_deref(), Some("Автор"));+ }- if cleaned.is_empty() {- continue;+ #[test]+ fn compressed_cp1251_via_lid() {+ let data = build_doc(+ &[TestPiece::Compressed(cp1251("Слава Україні\r"))],+ 0x0422,+ None,+ );+ assert_eq!(paragraph_texts(&parse(&data)), vec!["Слава Україні"]);+ }++ #[test]+ fn compressed_defaults_to_cp1252() {+ let data = build_doc(+ &[TestPiece::Compressed(b"Caf\xE9 \x93quoted\x94\r".to_vec())],+ 0x0409,+ None,+ );+ assert_eq!(paragraph_texts(&parse(&data)), vec!["Café \u{201C}quoted\u{201D}"]);+ }++ #[test]+ fn mixed_pieces_concatenate_in_cp_order() {+ let data = build_doc(+ &[+ TestPiece::Unicode("Перша частина "),+ TestPiece::Compressed(b"and ASCII tail\r".to_vec()),+ ],+ 0x0419,+ None,+ );+ assert_eq!(+ paragraph_texts(&parse(&data)),+ vec!["Перша частина and ASCII tail"]+ );+ }++ #[test]+ fn field_instructions_are_stripped() {+ let data = build_doc(+ &[TestPiece::Unicode(+ "See \u{13} HYPERLINK \"https://example.com\" \u{14}the site\u{15} now\r",+ )],+ 0x0409,+ None,+ );+ assert_eq!(paragraph_texts(&parse(&data)), vec!["See the site now"]);+ }++ #[test]+ fn cell_marks_and_line_breaks() {+ let data = build_doc(+ &[TestPiece::Unicode("cell one\u{7}cell two\u{7}line\u{b}break\r")],+ 0x0409,+ None,+ );+ assert_eq!(+ paragraph_texts(&parse(&data)),+ vec!["cell one", "cell two", "line\nbreak"]+ );+ }++ #[test]+ fn legacy_word_95_contiguous_text() {+ let text_bytes = cp1251("Стаття перша.\rСтаття друга.\r");+ let fc_min = 0x200usize;+ let mut word_doc = vec![0u8; fc_min];+ word_doc.extend_from_slice(&text_bytes);+ word_doc[0x00..0x02].copy_from_slice(&MAGIC_WORD_6_95.to_le_bytes());+ word_doc[0x06..0x08].copy_from_slice(&0x0419u16.to_le_bytes());+ word_doc[0x18..0x1C].copy_from_slice(&(fc_min as u32).to_le_bytes());+ word_doc[0x1C..0x20].copy_from_slice(&((fc_min + text_bytes.len()) as u32).to_le_bytes());+ let data = build_cfb(&[("WordDocument", &word_doc)]);+ assert_eq!(+ paragraph_texts(&parse(&data)),+ vec!["Стаття перша.", "Стаття друга."]+ );+ }++ #[test]+ fn malformed_piece_table_output_is_capped() {+ // 200 pieces of 100k chars all mapped to the same 100k file bytes; the+ // claimed 20M chars must clamp to MAX_TEXT_CHARS+ let text_len = 100_000u32;+ let num_pieces = 200u32;+ let mut word_doc = vec![0u8; TEXT_START];+ word_doc.extend_from_slice(&vec![b'A'; text_len as usize]);++ let mut plc = Vec::new();+ for k in 0..=num_pieces {+ plc.extend_from_slice(&(k * text_len).to_le_bytes());}+ let fc = (TEXT_START as u32 * 2) | 0x4000_0000;+ for _ in 0..num_pieces {+ plc.extend_from_slice(&0u16.to_le_bytes());+ plc.extend_from_slice(&fc.to_le_bytes());+ plc.extend_from_slice(&0u16.to_le_bytes());+ }+ let mut table = vec![0x02];+ table.extend_from_slice(&(plc.len() as u32).to_le_bytes());+ table.extend_from_slice(&plc);++ word_doc[0x00..0x02].copy_from_slice(&MAGIC_WORD_97.to_le_bytes());+ word_doc[0x0A..0x0C].copy_from_slice(&0x0200u16.to_le_bytes());+ word_doc[0x4C..0x50].copy_from_slice(&(num_pieces * text_len).to_le_bytes());+ word_doc[0x1A6..0x1AA].copy_from_slice(&(table.len() as u32).to_le_bytes());++ let data = build_cfb(&[("WordDocument", &word_doc), ("1Table", &table)]);+ let total: usize = paragraph_texts(&parse(&data)).iter().map(|t| t.len()).sum();+ assert!(total > 0);+ assert!(total <= MAX_TEXT_CHARS);+ }- blocks.push(Block::Paragraph(Paragraph {- kind: ParagraphKind::Normal,- inlines: vec![Inline::Text(cleaned)],- }));+ #[test]+ fn encrypted_documents_error() {+ let (mut word_doc, table) = build_word_doc_streams(&[TestPiece::Unicode("secret\r")], 0x0409);+ word_doc[0x0A..0x0C].copy_from_slice(&0x0300u16.to_le_bytes());+ let data = build_cfb(&[("WordDocument", &word_doc), ("1Table", &table)]);+ let err = DocProvider::new().parse_buffer(&data).unwrap_err();+ assert!(err.to_string().contains("encrypted"));}- blocks+ #[test]+ fn corrupt_piece_table_falls_back_to_fc_range() {+ let (mut word_doc, _) = build_word_doc_streams(&[TestPiece::Unicode("good text here\r")], 0x0409);+ word_doc[0x0A..0x0C].copy_from_slice(&0x1200u16.to_le_bytes());+ let fc_mac = word_doc.len() as u32;+ word_doc[0x18..0x1C].copy_from_slice(&(TEXT_START as u32).to_le_bytes());+ word_doc[0x1C..0x20].copy_from_slice(&fc_mac.to_le_bytes());+ let garbage_table = vec![0xFFu8; 64];+ let data = build_cfb(&[("WordDocument", &word_doc), ("1Table", &garbage_table)]);+ assert_eq!(paragraph_texts(&parse(&data)), vec!["good text here"]);+ }}diff --git a/apps/api/native/src/document/providers/docx.rs b/apps/api/native/src/document/providers/docx.rsindex 9bb168fb1..866f0bf6d 100644--- a/apps/api/native/src/document/providers/docx.rs+++ b/apps/api/native/src/document/providers/docx.rs@@ -1,10 +1,13 @@+//! DOCX (Office Open XML) provider.+use crate::document::model::*;use crate::document::providers::DocumentProvider;+use crate::document::xml::{attr, child, children, is_tag, read_zip_text, strip_bom};use chrono::{DateTime, Utc};use roxmltree::{Document as XmlDoc, Node};-use std::collections::HashMap;+use std::collections::{BTreeSet, HashMap};use std::error::Error;-use std::io::{Read, Seek};+use std::io::{Cursor, Read, Seek};use std::num::NonZeroU32;use zip::read::ZipArchive;@@ -16,62 +19,45 @@ impl DocxProvider {}}+/// Everything block parsing needs besides the XML itself.+#[derive(Clone, Copy)]+struct Ctx<'a> {+ rels: &'a Relationships,+ styles: &'a StylesInfo,+ size_buckets: &'a HashMap<String, Vec<u32>>,+ numbering: &'a NumberingInfo,+}+impl DocumentProvider for DocxProvider {fn parse_buffer(&self, data: &[u8]) -> Result<Document, Box<dyn Error + Send + Sync>> {- let cursor = std::io::Cursor::new(data);- let mut zip = ZipArchive::new(cursor)?;+ let mut zip = ZipArchive::new(Cursor::new(data))?;- let relationships = read_relationships(&mut zip, "word/_rels/document.xml.rels");+ let metadata = read_core_properties(&mut zip).unwrap_or_default();let styles = read_styles(&mut zip);let numbering = read_numbering(&mut zip);+ let rels = read_relationships(&mut zip, "word/_rels/document.xml.rels");let document_xml = read_zip_text(&mut zip, "word/document.xml").ok_or("Missing word/document.xml in document")?;let xml = XmlDoc::parse(strip_bom(&document_xml))?;- let metadata = read_core_properties(&mut zip).unwrap_or_default();+ let size_buckets = compute_style_size_buckets(&xml, &styles);+ let ctx = Ctx {+ rels: &rels,+ styles: &styles,+ size_buckets: &size_buckets,+ numbering: &numbering,+ };- let size_buckets = compute_style_size_buckets_for_doc(&xml, &styles);- let mut blocks = Vec::new();- if let Some(body) = xml.descendants().find(|n| is_tag(n, "body")) {- blocks = parse_block_children(- &body,- &relationships,- &styles,- &size_buckets,- &numbering,- &mut zip,- );- }+ let blocks = xml+ .descendants()+ .find(|n| is_tag(n, "body"))+ .map(|body| parse_blocks(&body, ctx))+ .unwrap_or_default();- let mut notes = Vec::new();- notes.extend(read_notes(- &mut zip,- "word/footnotes.xml",- "word/_rels/footnotes.xml.rels",- NoteKind::Footnote,- &styles,- &size_buckets,- &numbering,- ));- notes.extend(read_notes(- &mut zip,- "word/endnotes.xml",- "word/_rels/endnotes.xml.rels",- NoteKind::Endnote,- &styles,- &size_buckets,- &numbering,- ));-- let comments = read_comments(- &mut zip,- "word/comments.xml",- "word/_rels/comments.xml.rels",- &styles,- &size_buckets,- &numbering,- );+ let mut notes = read_notes(&mut zip, NoteKind::Footnote, ctx);+ notes.extend(read_notes(&mut zip, NoteKind::Endnote, ctx));+ let comments = read_comments(&mut zip, ctx);Ok(Document {blocks,@@ -86,18 +72,6 @@ impl DocumentProvider for DocxProvider {}}-fn read_zip_text<R: Read + std::io::Seek>(zip: &mut ZipArchive<R>, path: &str) -> Option<String> {- let mut file = zip.by_name(path).ok()?;- let mut s = String::new();- file.read_to_string(&mut s).ok()?;- Some(s)-}--fn strip_bom(s: &str) -> &str {- const BOM: char = '\u{FEFF}';- s.strip_prefix(BOM).unwrap_or(s)-}-#[derive(Debug, Clone, Default)]struct Relationships {targets: HashMap<String, String>,@@ -109,359 +83,235 @@ impl Relationships {}}-fn read_relationships<R: Read + std::io::Seek>(- zip: &mut ZipArchive<R>,- path: &str,-) -> Relationships {- let xml_text = match read_zip_text(zip, path) {- Some(s) => s,- None => return Relationships::default(),+fn read_relationships<R: Read + Seek>(zip: &mut ZipArchive<R>, path: &str) -> Relationships {+ let mut rels = Relationships::default();+ let Some(text) = read_zip_text(zip, path) else {+ return rels;};- let xml = match XmlDoc::parse(strip_bom(&xml_text)) {- Ok(d) => d,- Err(_) => return Relationships::default(),+ let Ok(xml) = XmlDoc::parse(strip_bom(&text)) else {+ return rels;};- let mut map = HashMap::new();for rel in xml.descendants().filter(|n| is_tag(n, "Relationship")) {- if let (Some(id), Some(target)) = (get_attr_local(&rel, "Id"), get_attr_local(&rel, "Target")) {- map.insert(id.to_string(), target.to_string());+ if let (Some(id), Some(target)) = (attr(&rel, "Id"), attr(&rel, "Target")) {+ rels.targets.insert(id.to_string(), target.to_string());}}- Relationships { targets: map }+ rels}-fn read_core_properties<R: Read + std::io::Seek>(- zip: &mut ZipArchive<R>,-) -> Option<DocumentMetadata> {+fn read_core_properties<R: Read + Seek>(zip: &mut ZipArchive<R>) -> Option<DocumentMetadata> {let text = read_zip_text(zip, "docProps/core.xml")?;let xml = XmlDoc::parse(strip_bom(&text)).ok()?;- let mut meta = DocumentMetadata::default();+ let element_text =+ |local: &str| xml.descendants().find(|n| is_tag(n, local)).and_then(|n| n.text());- if let Some(title) = xml- .descendants()- .find(|n| is_tag(n, "title"))- .and_then(|n| n.text())- {+ let mut meta = DocumentMetadata::default();+ if let Some(title) = element_text("title") {let trimmed = title.trim();if !trimmed.is_empty() {meta.title = Some(trimmed.to_string());}}- if let Some(author) = xml- .descendants()- .find(|n| is_tag(n, "creator"))- .and_then(|n| n.text())- {+ if let Some(author) = element_text("creator") {let trimmed = author.trim();if !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("unknown") {meta.author = Some(trimmed.to_string());}}- if let Some(created) = xml- .descendants()- .find(|n| is_tag(n, "created"))- .and_then(|n| n.text())- {- if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(created) {+ if let Some(created) = element_text("created") {+ if let Ok(dt) = DateTime::parse_from_rfc3339(created) {meta.created = Some(DateTime::<Utc>::from(dt));}}-Some(meta)}#[derive(Debug, Default)]struct StylesInfo {- heading_level_by_style_id: HashMap<String, u8>,+ outline_level_by_style_id: HashMap<String, u8>,name_by_style_id: HashMap<String, String>,default_size_by_style_id: HashMap<String, u32>,}fn read_styles<R: Read + Seek>(zip: &mut ZipArchive<R>) -> StylesInfo {- let text = match read_zip_text(zip, "word/styles.xml") {- Some(t) => t,- None => return StylesInfo::default(),+ let mut info = StylesInfo::default();+ let Some(text) = read_zip_text(zip, "word/styles.xml") else {+ return info;};- let doc = match XmlDoc::parse(strip_bom(&text)) {- Ok(d) => d,- Err(_) => return StylesInfo::default(),+ let Ok(xml) = XmlDoc::parse(strip_bom(&text)) else {+ return info;};- let mut info = StylesInfo::default();- for style in doc.descendants().filter(|n| is_tag(n, "style")) {- if get_attr_local(&style, "type") != Some("paragraph") {+ for style in xml.descendants().filter(|n| is_tag(n, "style")) {+ if attr(&style, "type") != Some("paragraph") {continue;}- let Some(style_id) = get_attr_local(&style, "styleId") else {+ let Some(style_id) = attr(&style, "styleId") else {continue;};- let style_id = style_id.to_string();- if let Some(name) = child(&style, "name").and_then(|n| get_attr_local(&n, "val")) {+ if let Some(name) = child(&style, "name").and_then(|n| attr(&n, "val")) {info.name_by_style_id- .insert(style_id.clone(), name.to_string());- }-- if let Some(rpr) = child(&style, "rPr") {- if let Some(sz) = child(&rpr, "sz").and_then(|n| get_attr_local(&n, "val")) {- if let Ok(v) = sz.parse::<u32>() {- info.default_size_by_style_id.insert(style_id.clone(), v);- }- }+ .insert(style_id.to_string(), name.to_string());}-- if let Some(ppr) = child(&style, "pPr") {- if let Some(ol) = child(&ppr, "outlineLvl").and_then(|n| get_attr_local(&n, "val")) {- if let Ok(v) = ol.parse::<u8>() {- info- .heading_level_by_style_id- .insert(style_id.clone(), (v + 1).min(6));- }- }+ if let Some(size) = child(&style, "rPr")+ .and_then(|rpr| child(&rpr, "sz"))+ .and_then(|n| attr(&n, "val"))+ .and_then(|v| v.parse::<u32>().ok())+ {+ info+ .default_size_by_style_id+ .insert(style_id.to_string(), size);}-- if !info.heading_level_by_style_id.contains_key(&style_id) {- let mut assigned: Option<u8> = None;- if let Some(name) = info.name_by_style_id.get(&style_id) {- assigned = parse_heading_level(name);- }- if assigned.is_none() {- assigned = parse_heading_level(&style_id);- }- if assigned.is_none() {- let name_l = info- .name_by_style_id- .get(&style_id)- .map(|s| s.to_ascii_lowercase())- .unwrap_or_default();- let id_l = style_id.to_ascii_lowercase();- if name_l.contains("title") || id_l.contains("title") {- assigned = Some(1);- } else if name_l.contains("heading") || id_l.contains("heading") {- assigned = Some(2);- }- }- if let Some(l) = assigned {- info.heading_level_by_style_id.insert(style_id, l);- }+ if let Some(level) = child(&style, "pPr")+ .and_then(|ppr| child(&ppr, "outlineLvl"))+ .and_then(|n| attr(&n, "val"))+ .and_then(|v| v.parse::<u8>().ok())+ {+ info+ .outline_level_by_style_id+ .insert(style_id.to_string(), (level + 1).min(6));}}info}-fn is_tag(node: &Node, local: &str) -> bool {- node.is_element() && node.tag_name().name() == local-}--fn get_attr_local<'a>(node: &Node<'a, 'a>, local: &str) -> Option<&'a str> {- node- .attributes()- .find(|a| {- let name = a.name();- match name.rsplit_once(':') {- Some((_, l)) => l == local,- None => name == local,- }- })- .map(|a| a.value())+enum StyleKind {+ Heading(u8),+ Blockquote,}-fn child<'a>(node: &Node<'a, 'a>, local: &str) -> Option<Node<'a, 'a>> {- node- .children()- .find(|n| n.is_element() && n.tag_name().name() == local)-}--fn children<'a, 'b>(- node: &Node<'a, 'a>,- local: &'b str,-) -> impl Iterator<Item = Node<'a, 'a>> + use<'a, 'b> {- node- .children()- .filter(move |n| n.is_element() && n.tag_name().name() == local)-}--fn parse_paragraph_with_listinfo(- node: &Node,- rels: &Relationships,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,- numbering: &NumberingInfo,-) -> Option<(Paragraph, Option<ListInfo>)> {- let kind = paragraph_kind(node, styles, size_buckets);- let base_style = paragraph_run_style(node);- let mut inlines = Vec::new();-- for child in node.children().filter(|n| n.is_element()) {- if is_tag(&child, "r") {- let run_inlines = parse_run(&child, rels, &base_style);- inlines.extend(run_inlines);- } else if is_tag(&child, "hyperlink") {- if let Some(link) = parse_hyperlink(&child, rels, &base_style) {- inlines.push(link);- }- } else if is_tag(&child, "bookmarkStart") {- if let Some(name) = get_attr_local(&child, "name") {- inlines.push(Inline::Bookmark(BookmarkId(name.to_string())));- }- } else if is_tag(&child, "br") {- inlines.push(Inline::LineBreak);- }+/// Heading or quote semantics of a paragraph style, from the style's outline+/// level when declared and name/id conventions otherwise.+fn style_kind(style_id: &str, styles: &StylesInfo) -> Option<StyleKind> {+ if let Some(level) = styles.outline_level_by_style_id.get(style_id) {+ return Some(StyleKind::Heading(*level));}- let list_info = paragraph_list_info(node, numbering);- Some((Paragraph { kind, inlines }, list_info))-}--fn paragraph_kind(- p: &Node,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,-) -> ParagraphKind {- let Some(ppr) = child(p, "pPr") else {- return ParagraphKind::Normal;- };-- if let Some(level) = child(&ppr, "outlineLvl").and_then(|n| get_attr_local(&n, "val")) {- if let Ok(v) = level.parse::<u8>() {- return ParagraphKind::Heading((v + 1).min(6));- }- }-- if let Some(style_id) = child(&ppr, "pStyle").and_then(|n| get_attr_local(&n, "val")) {- let mut base_level: Option<u8> = styles.heading_level_by_style_id.get(style_id).copied();-- if base_level.is_none() {- if let Some(name) = styles.name_by_style_id.get(style_id) {- if let Some(l) = parse_heading_level(name) {- base_level = Some(l);- }- if base_level.is_none() && name.to_ascii_lowercase().contains("quote") {- return ParagraphKind::Blockquote;- }- }- }- if base_level.is_none() {- if let Some(l) = parse_heading_level(style_id) {- base_level = Some(l);- }+ let name = styles.name_by_style_id.get(style_id);+ if let Some(name) = name {+ if let Some(level) = parse_heading_level(name) {+ return Some(StyleKind::Heading(level));}- if base_level.is_none() {- let id_l = style_id.to_ascii_lowercase();- let name_l = styles- .name_by_style_id- .get(style_id)- .map(|s| s.to_ascii_lowercase())- .unwrap_or_default();- if name_l.contains("title") || id_l.contains("title") {- base_level = Some(1);- } else if name_l.contains("heading") || id_l.contains("heading") {- base_level = Some(2);- } else if name_l.contains("quote") || id_l.contains("quote") {- return ParagraphKind::Blockquote;- }- }-- if let Some(mut level) = base_level {- let para_size = paragraph_effective_size(p, styles, style_id);- if let Some(buckets) = size_buckets.get(style_id) {- if let Some(size) = para_size {- if let Some(index) = buckets.iter().position(|&s| s == size) {- level = (level + index as u8).min(6);- }- }- }- return ParagraphKind::Heading(level);+ if name.to_ascii_lowercase().contains("quote") {+ return Some(StyleKind::Blockquote);}}+ if let Some(level) = parse_heading_level(style_id) {+ return Some(StyleKind::Heading(level));+ }- ParagraphKind::Normal+ let id_lower = style_id.to_ascii_lowercase();+ let name_lower = name.map(|s| s.to_ascii_lowercase()).unwrap_or_default();+ if name_lower.contains("title") || id_lower.contains("title") {+ Some(StyleKind::Heading(1))+ } else if name_lower.contains("heading") || id_lower.contains("heading") {+ Some(StyleKind::Heading(2))+ } else if name_lower.contains("quote") || id_lower.contains("quote") {+ Some(StyleKind::Blockquote)+ } else {+ None+ }}fn parse_heading_level(s: &str) -> Option<u8> {let lower = s.to_ascii_lowercase();- let idx = lower.find("heading")?;- let rest = &lower[idx + "heading".len()..];+ let rest = &lower[lower.find("heading")? + "heading".len()..];let digits: String = rest.chars().skip_while(|c| c.is_whitespace() || *c == '-').take_while(|c| c.is_ascii_digit()).collect();- if let Ok(n) = digits.parse::<u8>() {- if n >= 1 {- return Some(n.min(6));- }+ match digits.parse::<u8>() {+ Ok(n) if n >= 1 => Some(n.min(6)),+ _ => None,}- None}-fn paragraph_effective_size(p: &Node, styles: &StylesInfo, style_id: &str) -> Option<u32> {- let mut max_sz: Option<u32> = None;+fn paragraph_style_id<'a>(p: &Node<'a, 'a>) -> Option<&'a str> {+ child(p, "pPr")+ .and_then(|ppr| child(&ppr, "pStyle"))+ .and_then(|n| attr(&n, "val"))+}- if let Some(ppr) = child(p, "pPr") {- if let Some(rpr) = child(&ppr, "rPr") {- if let Some(sz) = child(&rpr, "sz").and_then(|n| get_attr_local(&n, "val")) {- if let Ok(v) = sz.parse::<u32>() {- max_sz = Some(max_sz.map_or(v, |m| m.max(v)));- }- }- }+fn paragraph_kind(p: &Node, ctx: Ctx) -> ParagraphKind {+ let Some(ppr) = child(p, "pPr") else {+ return ParagraphKind::Normal;+ };++ if let Some(level) = child(&ppr, "outlineLvl")+ .and_then(|n| attr(&n, "val"))+ .and_then(|v| v.parse::<u8>().ok())+ {+ return ParagraphKind::Heading((level + 1).min(6));}- for r in children(p, "r") {- if let Some(rpr) = child(&r, "rPr") {- if let Some(sz) = child(&rpr, "sz").and_then(|n| get_attr_local(&n, "val")) {- if let Ok(v) = sz.parse::<u32>() {- max_sz = Some(max_sz.map_or(v, |m| m.max(v)));+ let Some(style_id) = paragraph_style_id(p) else {+ return ParagraphKind::Normal;+ };+ match style_kind(style_id, ctx.styles) {+ Some(StyleKind::Blockquote) => ParagraphKind::Blockquote,+ Some(StyleKind::Heading(mut level)) => {+ // Same style at distinct font sizes: demote the smaller sizes.+ if let (Some(buckets), Some(size)) = (+ ctx.size_buckets.get(style_id),+ paragraph_effective_size(p, ctx.styles, style_id),+ ) {+ if let Some(index) = buckets.iter().position(|&s| s == size) {+ level = (level + index as u8).min(6);}}+ ParagraphKind::Heading(level)}+ None => ParagraphKind::Normal,}+}- max_sz.or_else(|| styles.default_size_by_style_id.get(style_id).copied())+fn paragraph_effective_size(p: &Node, styles: &StylesInfo, style_id: &str) -> Option<u32> {+ let run_sizes = children(p, "r")+ .filter_map(|r| child(&r, "rPr"))+ .chain(child(p, "pPr").and_then(|ppr| child(&ppr, "rPr")))+ .filter_map(|rpr| child(&rpr, "sz"))+ .filter_map(|n| attr(&n, "val"))+ .filter_map(|v| v.parse::<u32>().ok());+ run_sizes+ .max()+ .or_else(|| styles.default_size_by_style_id.get(style_id).copied())}-fn compute_style_size_buckets_for_doc(- xml: &XmlDoc,- styles: &StylesInfo,-) -> HashMap<String, Vec<u32>> {- let mut sets: HashMap<String, std::collections::BTreeSet<u32>> = HashMap::new();+/// Distinct font sizes seen per heading/title style, largest first.+fn compute_style_size_buckets(xml: &XmlDoc, styles: &StylesInfo) -> HashMap<String, Vec<u32>> {+ let mut sets: HashMap<String, BTreeSet<u32>> = HashMap::new();for p in xml.descendants().filter(|n| is_tag(n, "p")) {- let Some(style_id) = child(&p, "pPr")- .and_then(|n| child(&n, "pStyle"))- .and_then(|n| get_attr_local(&n, "val"))- else {+ let Some(style_id) = paragraph_style_id(&p) else {continue;};-- let id_l = style_id.to_ascii_lowercase();- let name_l = styles+ let id_lower = style_id.to_ascii_lowercase();+ let name_lower = styles.name_by_style_id.get(style_id).map(|s| s.to_ascii_lowercase()).unwrap_or_default();-- if !(id_l.contains("heading")- || id_l.contains("title")- || name_l.contains("heading")- || name_l.contains("title"))+ if !(id_lower.contains("heading")+ || id_lower.contains("title")+ || name_lower.contains("heading")+ || name_lower.contains("title")){continue;}-- if let Some(sz) = paragraph_effective_size(&p, styles, style_id) {- sets.entry(style_id.to_string()).or_default().insert(sz);+ if let Some(size) = paragraph_effective_size(&p, styles, style_id) {+ sets.entry(style_id.to_string()).or_default().insert(size);}}sets.into_iter()- .map(|(k, vset)| {- let mut v: Vec<u32> = vset.into_iter().collect();- v.sort_by(|a, b| b.cmp(a));- (k, v)+ .map(|(style_id, sizes)| {+ let mut sizes: Vec<u32> = sizes.into_iter().collect();+ sizes.reverse();+ (style_id, sizes)}).collect()}@@ -482,15 +332,6 @@ enum VerticalAlign {Subscript,}-#[derive(Clone, Copy)]-struct ResolvedRunStyle {- bold: bool,- italic: bool,- strike: bool,- code: bool,- vert_align: VerticalAlign,-}-impl RunStyle {fn merged(&self, overrides: &RunStyle) -> RunStyle {RunStyle {@@ -502,32 +343,32 @@ impl RunStyle {}}- fn resolve_with(&self, local: &RunStyle) -> ResolvedRunStyle {- ResolvedRunStyle {- bold: local.bold.or(self.bold).unwrap_or(false),- italic: local.italic.or(self.italic).unwrap_or(false),- strike: local.strike.or(self.strike).unwrap_or(false),- code: local.code.or(self.code).unwrap_or(false),- vert_align: local- .vert_align- .or(self.vert_align)- .unwrap_or(VerticalAlign::Baseline),+ fn apply(&self, local: &RunStyle, mut inlines: Vec<Inline>) -> Vec<Inline> {+ let resolved = self.merged(local);++ if resolved.code.unwrap_or(false) {+ let code_text: String = inlines+ .iter()+ .filter_map(|i| match i {+ Inline::Text(s) => Some(s.as_str()),+ _ => None,+ })+ .collect();+ if !code_text.is_empty() {+ return vec![Inline::Code(code_text)];+ }}- }-}-impl ResolvedRunStyle {- fn apply(self, mut inlines: Vec<Inline>) -> Vec<Inline> {- if self.strike {+ if resolved.strike.unwrap_or(false) {inlines = vec![Inline::Del(inlines)];}- if self.italic {+ if resolved.italic.unwrap_or(false) {inlines = vec![Inline::Em(inlines)];}- if self.bold {+ if resolved.bold.unwrap_or(false) {inlines = vec![Inline::Strong(inlines)];}- match self.vert_align {+ match resolved.vert_align.unwrap_or(VerticalAlign::Baseline) {VerticalAlign::Superscript => vec![Inline::Sup(inlines)],VerticalAlign::Subscript => vec![Inline::Sub(inlines)],VerticalAlign::Baseline => inlines,@@ -535,44 +376,36 @@ impl ResolvedRunStyle {}}-fn read_on_off(node: &Node) -> Option<bool> {- let value = get_attr_local(node, "val").map(|v| v.to_ascii_lowercase());- match value.as_deref() {- None => Some(true),- Some("0") | Some("false") | Some("off") => Some(false),- Some(_) => Some(true),- }+fn read_on_off(node: &Node) -> bool {+ !matches!(+ attr(node, "val").map(|v| v.to_ascii_lowercase()).as_deref(),+ Some("0") | Some("false") | Some("off")+ )}fn run_style_from_rpr(rpr: &Node) -> RunStyle {let mut style = RunStyle::default();-- if let Some(b) = child(rpr, "b").and_then(|n| read_on_off(&n)) {- style.bold = Some(b);+ if let Some(b) = child(rpr, "b") {+ style.bold = Some(read_on_off(&b));}- if let Some(i) = child(rpr, "i").and_then(|n| read_on_off(&n)) {- style.italic = Some(i);+ if let Some(i) = child(rpr, "i") {+ style.italic = Some(read_on_off(&i));}- if let Some(s) = child(rpr, "strike").and_then(|n| read_on_off(&n)) {- style.strike = Some(s);+ if let Some(s) = child(rpr, "strike") {+ style.strike = Some(read_on_off(&s));}- if let Some(rstyle) = child(rpr, "rStyle").and_then(|n| get_attr_local(&n, "val")) {+ if let Some(rstyle) = child(rpr, "rStyle").and_then(|n| attr(&n, "val")) {if rstyle.to_ascii_lowercase().contains("code") {style.code = Some(true);}}- if let Some(va) = child(rpr, "vertAlign").and_then(|n| get_attr_local(&n, "val")) {- let lower = va.to_ascii_lowercase();- let val = if lower == "sup" || lower == "superscript" {- VerticalAlign::Superscript- } else if lower == "sub" || lower == "subscript" {- VerticalAlign::Subscript- } else {- VerticalAlign::Baseline- };- style.vert_align = Some(val);+ if let Some(va) = child(rpr, "vertAlign").and_then(|n| attr(&n, "val")) {+ style.vert_align = Some(match va.to_ascii_lowercase().as_str() {+ "sup" | "superscript" => VerticalAlign::Superscript,+ "sub" | "subscript" => VerticalAlign::Subscript,+ _ => VerticalAlign::Baseline,+ });}-style}@@ -583,14 +416,36 @@ fn paragraph_run_style(p: &Node) -> RunStyle {.unwrap_or_default()}-fn parse_run(run: &Node, _rels: &Relationships, base_style: &RunStyle) -> Vec<Inline> {+fn parse_paragraph(node: &Node, ctx: Ctx) -> Paragraph {+ let kind = paragraph_kind(node, ctx);+ let base_style = paragraph_run_style(node);+ let mut inlines = Vec::new();++ for c in node.children().filter(|n| n.is_element()) {+ if is_tag(&c, "r") {+ inlines.extend(parse_run(&c, &base_style));+ } else if is_tag(&c, "hyperlink") {+ if let Some(link) = parse_hyperlink(&c, ctx.rels, &base_style) {+ inlines.push(link);+ }+ } else if is_tag(&c, "bookmarkStart") {+ if let Some(name) = attr(&c, "name") {+ inlines.push(Inline::Bookmark(BookmarkId(name.to_string())));+ }+ } else if is_tag(&c, "br") {+ inlines.push(Inline::LineBreak);+ }+ }++ Paragraph { kind, inlines }+}++fn parse_run(run: &Node, base_style: &RunStyle) -> Vec<Inline> {let local_style = child(run, "rPr").map(|rpr| run_style_from_rpr(&rpr)).unwrap_or_default();- let resolved = base_style.resolve_with(&local_style);let mut out = Vec::new();-for c in run.children().filter(|n| n.is_element()) {if is_tag(&c, "t") {if let Some(text) = c.text() {@@ -601,41 +456,28 @@ fn parse_run(run: &Node, _rels: &Relationships, base_style: &RunStyle) -> Vec<In} else if is_tag(&c, "tab") {out.push(Inline::Text("\t".to_string()));} else if is_tag(&c, "footnoteReference") {- if let Some(id) = get_attr_local(&c, "id") {+ if let Some(id) = attr(&c, "id") {out.push(Inline::FootnoteRef(NoteId(id.to_string())));}} else if is_tag(&c, "endnoteReference") {- if let Some(id) = get_attr_local(&c, "id") {+ if let Some(id) = attr(&c, "id") {out.push(Inline::EndnoteRef(NoteId(id.to_string())));}} else if is_tag(&c, "commentReference") {- if let Some(id) = get_attr_local(&c, "id") {+ if let Some(id) = attr(&c, "id") {out.push(Inline::CommentRef(CommentId(id.to_string())));}}}- if resolved.code {- let code_text: String = out- .iter()- .filter_map(|i| match i {- Inline::Text(s) => Some(s.as_str()),- _ => None,- })- .collect();- if !code_text.is_empty() {- return vec![Inline::Code(code_text)];- }- }-- resolved.apply(out)+ base_style.apply(&local_style, out)}fn parse_hyperlink(node: &Node, rels: &Relationships, base_style: &RunStyle) -> Option<Inline> {- let href = if let Some(id) = get_attr_local(node, "id") {+ let href = if let Some(id) = attr(node, "id") {rels.get(id).map(|s| s.to_string())} else {- get_attr_local(node, "anchor").map(|anchor| format!("#{anchor}"))+ attr(node, "anchor").map(|anchor| format!("#{anchor}"))}?;let link_style = child(node, "rPr")@@ -643,55 +485,78 @@ fn parse_hyperlink(node: &Node, rels: &Relationships, base_style: &RunStyle) ->.unwrap_or_default();let combined_style = base_style.merged(&link_style);- let mut children = Vec::new();- for child in node.children().filter(|n| n.is_element()) {- if is_tag(&child, "r") {- children.extend(parse_run(&child, rels, &combined_style));- }+ let mut link_children = Vec::new();+ for run in children(node, "r") {+ link_children.extend(parse_run(&run, &combined_style));}- Some(Inline::Link { href, children })+ Some(Inline::Link {+ href,+ children: link_children,+ })+}++fn parse_blocks(parent: &Node, ctx: Ctx) -> Vec<Block> {+ let nodes: Vec<Node> = parent.children().filter(|n| n.is_element()).collect();+ let mut out = Vec::new();+ let mut i = 0;++ while i < nodes.len() {+ let node = &nodes[i];+ if is_tag(node, "p") {+ if paragraph_list_info(node, ctx.numbering).is_some() {+ let (list, next_i) = parse_list(&nodes, i, ctx);+ if !list.items.is_empty() {+ out.push(Block::List(list));+ }+ i = next_i;+ continue;+ }+ if let Some(image) = parse_image_paragraph(node, ctx.rels) {+ out.push(Block::Image(image));+ } else {+ let para = parse_paragraph(node, ctx);+ if has_visible_content(¶.inlines) {+ out.push(Block::Paragraph(para));+ }+ }+ } else if is_tag(node, "tbl") {+ out.push(Block::Table(parse_table(node, ctx)));+ }+ i += 1;+ }+ out}-fn parse_table<R: Read + Seek>(- node: &Node,- rels: &Relationships,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,- numbering: &NumberingInfo,- zip: &mut ZipArchive<R>,-) -> Option<Table> {+fn parse_table(node: &Node, ctx: Ctx) -> Table {let mut rows = Vec::new();for tr in children(node, "tr") {- let kind = table_row_kind(&tr);- let mut cells = Vec::new();- for tc in children(&tr, "tc") {- let cell_blocks = parse_block_children(&tc, rels, styles, size_buckets, numbering, zip);- let cell = TableCell {- blocks: cell_blocks,- colspan: NonZeroU32::new(1).unwrap(),- rowspan: NonZeroU32::new(1).unwrap(),- };- cells.push(cell);- }- rows.push(TableRow { cells, kind });+ let header = child(&tr, "trPr")+ .and_then(|trpr| child(&trpr, "tblHeader"))+ .is_some();+ let cells = children(&tr, "tc")+ .map(|tc| TableCell {+ blocks: parse_blocks(&tc, ctx),+ colspan: NonZeroU32::MIN,+ rowspan: NonZeroU32::MIN,+ })+ .collect();+ rows.push(TableRow {+ cells,+ kind: if header {+ TableRowKind::Header+ } else {+ TableRowKind::Body+ },+ });}- if !rows.is_empty() && rows.iter().any(|r| matches!(r.kind, TableRowKind::Header)) {+ if rows.iter().any(|r| matches!(r.kind, TableRowKind::Header)) {if let Some(last) = rows.last_mut() {last.kind = TableRowKind::Footer;}}- Some(Table { rows })-}--fn table_row_kind(tr: &Node) -> TableRowKind {- if let Some(trpr) = child(tr, "trPr") {- if child(&trpr, "tblHeader").is_some() {- return TableRowKind::Header;- }- }- TableRowKind::Body+ Table { rows }}#[derive(Debug, Clone, PartialEq, Eq)]@@ -709,224 +574,133 @@ struct NumberingInfo {impl NumberingInfo {fn list_type(&self, num_id: &str, ilvl: &str) -> Option<ListType> {- let abs = self.num_to_abstract.get(num_id)?;- let levels = self.abstract_levels.get(abs)?;- levels.get(ilvl).copied()+ self+ .abstract_levels+ .get(self.num_to_abstract.get(num_id)?)?+ .get(ilvl)+ .copied()}}fn read_numbering<R: Read + Seek>(zip: &mut ZipArchive<R>) -> NumberingInfo {- let text = match read_zip_text(zip, "word/numbering.xml") {- Some(t) => t,- None => return NumberingInfo::default(),+ let mut info = NumberingInfo::default();+ let Some(text) = read_zip_text(zip, "word/numbering.xml") else {+ return info;};- let doc = match XmlDoc::parse(strip_bom(&text)) {- Ok(d) => d,- Err(_) => return NumberingInfo::default(),+ let Ok(xml) = XmlDoc::parse(strip_bom(&text)) else {+ return info;};- let mut info = NumberingInfo::default();-- for num in doc.descendants().filter(|n| is_tag(n, "num")) {- if let Some(num_id) = get_attr_local(&num, "numId") {- if let Some(abs) = child(&num, "abstractNumId").and_then(|n| get_attr_local(&n, "val")) {- info- .num_to_abstract- .insert(num_id.to_string(), abs.to_string());- }+ for num in xml.descendants().filter(|n| is_tag(n, "num")) {+ if let (Some(num_id), Some(abs)) = (+ attr(&num, "numId"),+ child(&num, "abstractNumId").and_then(|n| attr(&n, "val")),+ ) {+ info+ .num_to_abstract+ .insert(num_id.to_string(), abs.to_string());}}- for abs in doc.descendants().filter(|n| is_tag(n, "abstractNum")) {- if let Some(abs_id) = get_attr_local(&abs, "abstractNumId") {- let mut levels: HashMap<String, ListType> = HashMap::new();- for lvl in children(&abs, "lvl") {- if let Some(ilvl) = get_attr_local(&lvl, "ilvl") {- let fmt = child(&lvl, "numFmt").and_then(|n| get_attr_local(&n, "val"));- let list_type = match fmt.unwrap_or("") {- "bullet" => ListType::Unordered,- _ => ListType::Ordered,- };- levels.insert(ilvl.to_string(), list_type);- }+ for abs in xml.descendants().filter(|n| is_tag(n, "abstractNum")) {+ let Some(abs_id) = attr(&abs, "abstractNumId") else {+ continue;+ };+ let mut levels = HashMap::new();+ for lvl in children(&abs, "lvl") {+ if let Some(ilvl) = attr(&lvl, "ilvl") {+ let fmt = child(&lvl, "numFmt").and_then(|n| attr(&n, "val"));+ let list_type = match fmt.unwrap_or("") {+ "bullet" => ListType::Unordered,+ _ => ListType::Ordered,+ };+ levels.insert(ilvl.to_string(), list_type);}- info.abstract_levels.insert(abs_id.to_string(), levels);}+ info.abstract_levels.insert(abs_id.to_string(), levels);}-info}fn paragraph_list_info(p: &Node, numbering: &NumberingInfo) -> Option<ListInfo> {- let ppr = child(p, "pPr")?;- let numpr = child(&ppr, "numPr")?;- let ilvl_str = child(&numpr, "ilvl").and_then(|n| get_attr_local(&n, "val"))?;- let num_id = child(&numpr, "numId").and_then(|n| get_attr_local(&n, "val"))?;- let ilvl: u32 = ilvl_str.parse().unwrap_or(0);- let list_type = numbering- .list_type(num_id, ilvl_str)- .unwrap_or(ListType::Unordered);+ let numpr = child(p, "pPr").and_then(|ppr| child(&ppr, "numPr"))?;+ let ilvl_str = child(&numpr, "ilvl").and_then(|n| attr(&n, "val"))?;+ let num_id = child(&numpr, "numId").and_then(|n| attr(&n, "val"))?;Some(ListInfo {- list_type,+ list_type: numbering+ .list_type(num_id, ilvl_str)+ .unwrap_or(ListType::Unordered),num_id: num_id.to_string(),- ilvl,+ ilvl: ilvl_str.parse().unwrap_or(0),})}-fn parse_block_children<R: Read + Seek>(- parent: &Node,- rels: &Relationships,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,- numbering: &NumberingInfo,- zip: &mut ZipArchive<R>,-) -> Vec<Block> {- let nodes: Vec<Node> = parent.children().filter(|n| n.is_element()).collect();- let mut out: Vec<Block> = Vec::new();- let mut i = 0usize;-- while i < nodes.len() {- let node = &nodes[i];- if is_tag(node, "p") {- if paragraph_list_info(node, numbering).is_some() {- let (list, new_i) = parse_list(&nodes, i, rels, styles, size_buckets, numbering, zip);- if !list.items.is_empty() {- out.push(Block::List(list));- }- i = new_i;- continue;- }- if let Some(image) = parse_image_paragraph(node, rels, zip) {- out.push(Block::Image(image));- i += 1;- continue;- }- if let Some((para, _)) =- parse_paragraph_with_listinfo(node, rels, styles, size_buckets, numbering)- {- if paragraph_has_visible_content(¶) {- out.push(Block::Paragraph(para));- }- }- i += 1;- } else if is_tag(node, "tbl") {- if let Some(table) = parse_table(node, rels, styles, size_buckets, numbering, zip) {- out.push(Block::Table(table));- }- i += 1;- } else {- i += 1;- }- }- out-}--fn parse_list<R: Read + Seek>(- nodes: &[Node],- mut i: usize,- rels: &Relationships,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,- numbering: &NumberingInfo,- zip: &mut ZipArchive<R>,-) -> (List, usize) {- let first_info =- paragraph_list_info(&nodes[i], numbering).expect("parse_list called at non-list paragraph");- let base_ilvl = first_info.ilvl;- let base_num_id = first_info.num_id.clone();- let base_type = first_info.list_type;-+/// Consumes consecutive numbered paragraphs at one level into a list,+/// recursing for deeper levels. Returns the list and the next unconsumed+/// node index.+fn parse_list(nodes: &[Node], mut i: usize, ctx: Ctx) -> (List, usize) {let mut list = List {items: Vec::new(),- list_type: base_type,+ list_type: ListType::Unordered,+ };+ let Some(base) = nodes.get(i).and_then(|n| paragraph_list_info(n, ctx.numbering)) else {+ return (list, i + 1);};+ list.list_type = base.list_type;while i < nodes.len() {let node = &nodes[i];if !is_tag(node, "p") {break;}- let info = match paragraph_list_info(node, numbering) {- Some(x) => x,- None => break,+ let Some(info) = paragraph_list_info(node, ctx.numbering) else {+ break;};- if info.ilvl < base_ilvl {+ if info.ilvl < base.ilvl+ || (info.ilvl == base.ilvl+ && (info.list_type != base.list_type || info.num_id != base.num_id))+ {break;}- if info.ilvl == base_ilvl && (info.list_type != base_type || info.num_id != base_num_id) {+ if info.ilvl > base.ilvl {+ // deeper level with no parent item yet; let the caller handle itbreak;}- if info.ilvl == base_ilvl {- let mut blocks: Vec<Block> = Vec::new();- if let Some(image) = parse_image_paragraph(node, rels, zip) {- blocks.push(Block::Image(image));- } else if let Some((para, _)) =- parse_paragraph_with_listinfo(node, rels, styles, size_buckets, numbering)- {- if paragraph_has_visible_content(¶) {- blocks.push(Block::Paragraph(para));- }+ let mut blocks = Vec::new();+ if let Some(image) = parse_image_paragraph(node, ctx.rels) {+ blocks.push(Block::Image(image));+ } else {+ let para = parse_paragraph(node, ctx);+ if has_visible_content(¶.inlines) {+ blocks.push(Block::Paragraph(para));}- list.items.push(ListItem { blocks });- i += 1;+ }+ list.items.push(ListItem { blocks });+ i += 1;- loop {- if i >= nodes.len() {- break;- }- let node2 = &nodes[i];- if !is_tag(node2, "p") {- break;- }- match paragraph_list_info(node2, numbering) {- Some(sub) if sub.ilvl > base_ilvl => {- let (sublist, new_i) = parse_list(nodes, i, rels, styles, size_buckets, numbering, zip);- if let Some(last) = list.items.last_mut() {- last.blocks.push(Block::List(sublist));- }- i = new_i;+ while i < nodes.len() && is_tag(&nodes[i], "p") {+ match paragraph_list_info(&nodes[i], ctx.numbering) {+ Some(sub) if sub.ilvl > base.ilvl => {+ let (sublist, next_i) = parse_list(nodes, i, ctx);+ if let Some(last) = list.items.last_mut() {+ last.blocks.push(Block::List(sublist));}- _ => break,+ i = next_i;}+ _ => break,}+ }- if list.items.last().is_some_and(|last| last.blocks.is_empty()) {- list.items.pop();- }+ if list.items.last().is_some_and(|last| last.blocks.is_empty()) {+ list.items.pop();}}(list, i)}-fn paragraph_has_visible_content(p: &Paragraph) -> bool {- inlines_have_visible_content(&p.inlines)-}--fn inlines_have_visible_content(inlines: &[Inline]) -> bool {- inlines.iter().any(inline_is_visible)-}--fn inline_is_visible(i: &Inline) -> bool {- match i {- Inline::Text(t) => !t.trim().is_empty(),- Inline::LineBreak => false,- Inline::Link { children, .. } => inlines_have_visible_content(children),- Inline::Strong(c) | Inline::Em(c) | Inline::Del(c) | Inline::Sup(c) | Inline::Sub(c) => {- inlines_have_visible_content(c)- }- Inline::Code(c) => !c.trim().is_empty(),- Inline::FootnoteRef(_) | Inline::EndnoteRef(_) | Inline::CommentRef(_) => true,- Inline::Bookmark(_) => false,- }-}--fn parse_image_paragraph<R: Read + Seek>(- p: &Node,- rels: &Relationships,- zip: &mut ZipArchive<R>,-) -> Option<Image> {+fn parse_image_paragraph(p: &Node, rels: &Relationships) -> Option<Image> {let has_text = p.descendants().filter(|n| is_tag(n, "t"))@@ -936,139 +710,94 @@ fn parse_image_paragraph<R: Read + Seek>(}if let Some(drawing) = p.descendants().find(|n| is_tag(n, "drawing")) {- if let Some(img) = image_from_drawing(&drawing, rels, zip) {- return Some(img);- }+ let blip = drawing.descendants().find(|n| is_tag(n, "blip"))?;+ let rel_id = attr(&blip, "embed").or_else(|| attr(&blip, "link"))?;+ let alt = drawing+ .descendants()+ .find(|n| is_tag(n, "docPr"))+ .and_then(|n| attr(&n, "descr").or_else(|| attr(&n, "title")))+ .map(|s| s.to_string());+ return external_image(rels.get(rel_id)?, alt);}if let Some(pict) = p.descendants().find(|n| is_tag(n, "pict")) {- if let Some(img) = image_from_vml(&pict, rels, zip) {- return Some(img);- }+ let imagedata = pict.descendants().find(|n| is_tag(n, "imagedata"))?;+ let rel_id = attr(&imagedata, "id")?;+ let alt = attr(&imagedata, "title").map(|s| s.to_string());+ return external_image(rels.get(rel_id)?, alt);}None}-fn image_from_drawing<R: Read + Seek>(- drawing: &Node,- rels: &Relationships,- zip: &mut ZipArchive<R>,-) -> Option<Image> {- let blip = drawing.descendants().find(|n| is_tag(n, "blip"))?;- let rel_id = get_attr_local(&blip, "embed").or_else(|| get_attr_local(&blip, "link"))?;- let alt = drawing- .descendants()- .find(|n| is_tag(n, "docPr"))- .and_then(|n| get_attr_local(&n, "descr").or_else(|| get_attr_local(&n, "title")))- .map(|s| s.to_string());- image_from_relationship_id(rel_id, rels, zip, alt)-}--fn image_from_vml<R: Read + Seek>(- pict: &Node,- rels: &Relationships,- zip: &mut ZipArchive<R>,-) -> Option<Image> {- let imagedata = pict.descendants().find(|n| is_tag(n, "imagedata"))?;- let rel_id = get_attr_local(&imagedata, "id")?;- let alt = get_attr_local(&imagedata, "title").map(|s| s.to_string());- image_from_relationship_id(rel_id, rels, zip, alt)-}--fn image_from_relationship_id<R: Read + Seek>(- rid: &str,- rels: &Relationships,- _zip: &mut ZipArchive<R>,- alt: Option<String>,-) -> Option<Image> {- let target = rels.get(rid)?;- // only include external images (http/https URLs)+/// Only external (http/https) images are representable in the output.+fn external_image(target: &str, alt: Option<String>) -> Option<Image> {if target.starts_with("http://") || target.starts_with("https://") {- return Some(Image {+ Some(Image {src: target.to_string(),alt,- });+ })+ } else {+ None}- None}-fn read_notes<R: Read + Seek>(- zip: &mut ZipArchive<R>,- xml_path: &str,- rels_path: &str,- kind: NoteKind,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,- numbering: &NumberingInfo,-) -> Vec<Note> {- let text = match read_zip_text(zip, xml_path) {- Some(t) => t,- None => return Vec::new(),+fn read_notes<R: Read + Seek>(zip: &mut ZipArchive<R>, kind: NoteKind, ctx: Ctx) -> Vec<Note> {+ let (xml_path, rels_path, root_tag) = match kind {+ NoteKind::Footnote => (+ "word/footnotes.xml",+ "word/_rels/footnotes.xml.rels",+ "footnote",+ ),+ NoteKind::Endnote => ("word/endnotes.xml", "word/_rels/endnotes.xml.rels", "endnote"),};- let doc = match XmlDoc::parse(strip_bom(&text)) {- Ok(d) => d,- Err(_) => return Vec::new(),+ let Some(text) = read_zip_text(zip, xml_path) else {+ return Vec::new();+ };+ let Ok(xml) = XmlDoc::parse(strip_bom(&text)) else {+ return Vec::new();};let rels = read_relationships(zip, rels_path);+ let ctx = Ctx { rels: &rels, ..ctx };let mut notes = Vec::new();- let root_tag = match kind {- NoteKind::Footnote => "footnote",- NoteKind::Endnote => "endnote",- };- for n in doc.descendants().filter(|n| is_tag(n, root_tag)) {- let Some(id) = get_attr_local(&n, "id") else {+ for n in xml.descendants().filter(|n| is_tag(n, root_tag)) {+ let Some(id) = attr(&n, "id") else {continue;};-- if let Some(t) = get_attr_local(&n, "type") {- if t == "separator" || t == "continuationSeparator" {- continue;- }+ if matches!(attr(&n, "type"), Some("separator" | "continuationSeparator")) {+ continue;}- let blocks = parse_block_children(&n, &rels, styles, size_buckets, numbering, zip);notes.push(Note {id: NoteId(id.to_string()),kind,- blocks,+ blocks: parse_blocks(&n, ctx),});}notes}-fn read_comments<R: Read + Seek>(- zip: &mut ZipArchive<R>,- xml_path: &str,- rels_path: &str,- styles: &StylesInfo,- size_buckets: &HashMap<String, Vec<u32>>,- numbering: &NumberingInfo,-) -> Vec<Comment> {- let text = match read_zip_text(zip, xml_path) {- Some(t) => t,- None => return Vec::new(),+fn read_comments<R: Read + Seek>(zip: &mut ZipArchive<R>, ctx: Ctx) -> Vec<Comment> {+ let Some(text) = read_zip_text(zip, "word/comments.xml") else {+ return Vec::new();};- let doc = match XmlDoc::parse(strip_bom(&text)) {- Ok(d) => d,- Err(_) => return Vec::new(),+ let Ok(xml) = XmlDoc::parse(strip_bom(&text)) else {+ return Vec::new();};- let rels = read_relationships(zip, rels_path);+ let rels = read_relationships(zip, "word/_rels/comments.xml.rels");+ let ctx = Ctx { rels: &rels, ..ctx };- let mut out = Vec::new();- for c in doc.descendants().filter(|n| is_tag(n, "comment")) {- let Some(id) = get_attr_local(&c, "id") else {+ let mut comments = Vec::new();+ for c in xml.descendants().filter(|n| is_tag(n, "comment")) {+ let Some(id) = attr(&c, "id") else {continue;};-- let author = get_attr_local(&c, "author").map(|s| s.to_string());- let initials = get_attr_local(&c, "initials").map(|s| s.to_string());- let blocks = parse_block_children(&c, &rels, styles, size_buckets, numbering, zip);- out.push(Comment {+ comments.push(Comment {id: CommentId(id.to_string()),- author_name: author,- author_initials: initials,- blocks,+ author_name: attr(&c, "author").map(|s| s.to_string()),+ author_initials: attr(&c, "initials").map(|s| s.to_string()),+ blocks: parse_blocks(&c, ctx),});}- out+ comments}+diff --git a/apps/api/native/src/document/providers/odt.rs b/apps/api/native/src/document/providers/odt.rsindex 0d5cbc8c6..d894face8 100644--- a/apps/api/native/src/document/providers/odt.rs+++ b/apps/api/native/src/document/providers/odt.rs@@ -1,10 +1,13 @@+//! ODT (OpenDocument text) provider.+use crate::document::model::*;use crate::document::providers::DocumentProvider;+use crate::document::xml::{attr, child, children, is_tag, read_zip_text, strip_bom};use chrono::{DateTime, Utc};use roxmltree::{Document as XmlDoc, Node};-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::error::Error;-use std::io::{Read, Seek};+use std::io::{Cursor, Read, Seek};use std::num::NonZeroU32;use zip::read::ZipArchive;@@ -18,33 +21,31 @@ impl OdtProvider {impl DocumentProvider for OdtProvider {fn parse_buffer(&self, data: &[u8]) -> Result<Document, Box<dyn Error + Send + Sync>> {- let cursor = std::io::Cursor::new(data);- let mut zip = ZipArchive::new(cursor)?;+ let mut zip = ZipArchive::new(Cursor::new(data))?;- let meta = read_meta(&mut zip).unwrap_or_default();+ let metadata = read_meta(&mut zip).unwrap_or_default();let styles = read_styles(&mut zip);let content =read_zip_text(&mut zip, "content.xml").ok_or("Missing content.xml in document")?;let xml = XmlDoc::parse(strip_bom(&content))?;- let mut notes: Vec<Note> = Vec::new();- let mut comments: Vec<Comment> = Vec::new();- let mut blocks: Vec<Block> = Vec::new();-- let body_text = xml+ let mut parser = Parser {+ styles: &styles,+ notes: Vec::new(),+ comments: Vec::new(),+ };+ let blocks = xml.descendants()- .find(|n| is_tag(n, "text") && n.ancestors().any(|a| is_tag(&a, "body")));-- if let Some(text_node) = body_text {- blocks = parse_block_children_odt(&text_node, &styles, &mut notes, &mut comments, &mut zip);- }+ .find(|n| is_tag(n, "text") && n.ancestors().any(|a| is_tag(&a, "body")))+ .map(|body| parser.parse_blocks(&body))+ .unwrap_or_default();Ok(Document {blocks,- metadata: meta,- notes,- comments,+ metadata,+ notes: parser.notes,+ comments: parser.comments,})}@@ -53,25 +54,38 @@ impl DocumentProvider for OdtProvider {}}-fn read_zip_text<R: Read + Seek>(zip: &mut ZipArchive<R>, path: &str) -> Option<String> {- let mut file = zip.by_name(path).ok()?;- let mut s = String::new();- file.read_to_string(&mut s).ok()?;- Some(s)-}+fn read_meta<R: Read + Seek>(zip: &mut ZipArchive<R>) -> Option<DocumentMetadata> {+ let text = read_zip_text(zip, "meta.xml")?;+ let xml = XmlDoc::parse(strip_bom(&text)).ok()?;+ let element_text =+ |local: &str| xml.descendants().find(|n| is_tag(n, local)).and_then(|n| n.text());-fn strip_bom(s: &str) -> &str {- const BOM: char = '\u{FEFF}';- s.strip_prefix(BOM).unwrap_or(s)+ let mut meta = DocumentMetadata::default();+ if let Some(title) = element_text("title") {+ if !title.trim().is_empty() {+ meta.title = Some(title.to_string());+ }+ }+ if let Some(author) = element_text("creator").or_else(|| element_text("initial-creator")) {+ let trimmed = author.trim();+ if !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("unknown") {+ meta.author = Some(trimmed.to_string());+ }+ }+ if let Some(created) = element_text("creation-date") {+ if let Ok(dt) = DateTime::parse_from_rfc3339(created) {+ meta.created = Some(DateTime::<Utc>::from(dt));+ }+ }+ Some(meta)}-#[derive(Debug, Default, Clone)]+#[derive(Debug, Default)]struct OdtStylesInfo {- paragraph_names: HashMap<String, String>,+ paragraph_style_names: HashSet<String>,paragraph_outline_level: HashMap<String, u8>,paragraph_text_props: HashMap<String, TextStyleProps>,text_props: HashMap<String, TextStyleProps>,- text_font_name: HashMap<String, String>,list_is_ordered: HashMap<String, bool>,}@@ -87,84 +101,62 @@ struct TextStyleProps {fn read_styles<R: Read + Seek>(zip: &mut ZipArchive<R>) -> OdtStylesInfo {let mut info = OdtStylesInfo::default();-- if let Some(t) = read_zip_text(zip, "styles.xml") {- if let Ok(doc) = XmlDoc::parse(strip_bom(&t)) {- harvest_styles_from_doc(&doc, &mut info);- }- }- if let Some(t) = read_zip_text(zip, "content.xml") {- if let Ok(doc) = XmlDoc::parse(strip_bom(&t)) {- harvest_styles_from_doc(&doc, &mut info);+ for path in ["styles.xml", "content.xml"] {+ if let Some(text) = read_zip_text(zip, path) {+ if let Ok(xml) = XmlDoc::parse(strip_bom(&text)) {+ harvest_styles(&xml, &mut info);+ }}}info}-fn harvest_styles_from_doc(doc: &XmlDoc, out: &mut OdtStylesInfo) {- for s in doc.descendants().filter(|n| is_tag(n, "style")) {- let Some(family) = get_attr_local(&s, "family") else {+fn harvest_styles(xml: &XmlDoc, out: &mut OdtStylesInfo) {+ for style in xml.descendants().filter(|n| is_tag(n, "style")) {+ let (Some(family), Some(name)) = (attr(&style, "family"), attr(&style, "name")) else {continue;};- let Some(name) = get_attr_local(&s, "name") else {- continue;- };- let lname = name.to_string();-- if family == "paragraph" {- out.paragraph_names.insert(lname.clone(), lname.clone());- if let Some(ppr) = child(&s, "paragraph-properties") {- if let Some(ol) = get_attr_local(&ppr, "outline-level") {- if let Ok(v) = ol.parse::<u8>() {- out.paragraph_outline_level.insert(lname.clone(), v.min(6));- }+ match family {+ "paragraph" => {+ out.paragraph_style_names.insert(name.to_string());++ let outline_level = child(&style, "paragraph-properties")+ .and_then(|pp| attr(&pp, "outline-level"))+ .and_then(|v| v.parse::<u8>().ok())+ .map(|v| v.min(6))+ .or_else(|| attr(&style, "parent-style-name").and_then(parse_heading_level));+ if let Some(level) = outline_level {+ out.paragraph_outline_level.insert(name.to_string(), level);}- }- if !out.paragraph_outline_level.contains_key(&lname) {- if let Some(parent) = get_attr_local(&s, "parent-style-name") {- if let Some(lv) = parse_odt_heading_level(parent) {- out.paragraph_outline_level.insert(lname.clone(), lv);- }+ if let Some(tp) = child(&style, "text-properties") {+ out+ .paragraph_text_props+ .insert(name.to_string(), parse_text_properties(&tp));}}-- if let Some(tp) = child(&s, "text-properties") {- let mut props = parse_text_properties(&tp);- if let Some(v) = get_attr_local(&tp, "font-name") {- if v.to_ascii_lowercase().contains("courier") || v.to_ascii_lowercase().contains("mono") {- props.code = true;- }- out.text_font_name.insert(lname.clone(), v.to_string());+ "text" => {+ if let Some(tp) = child(&style, "text-properties") {+ out+ .text_props+ .insert(name.to_string(), parse_text_properties(&tp));}- out.paragraph_text_props.insert(lname.clone(), props);}- } else if family == "text" {- if let Some(tp) = child(&s, "text-properties") {- let mut props = parse_text_properties(&tp);- if let Some(v) = get_attr_local(&tp, "font-name") {- if v.to_ascii_lowercase().contains("courier") || v.to_ascii_lowercase().contains("mono") {- props.code = true;- }- out.text_font_name.insert(lname.clone(), v.to_string());- }- out.text_props.insert(lname.clone(), props);+ "list" => {+ let is_ordered = style+ .children()+ .any(|c| is_tag(&c, "list-level-style-number"));+ out.list_is_ordered.insert(name.to_string(), is_ordered);}- } else if family == "list" {- let is_ordered = s- .children()- .filter(|n| n.is_element())- .any(|child_n| is_tag(&child_n, "list-level-style-number"));- out.list_is_ordered.insert(lname.clone(), is_ordered);+ _ => {}}}- for ls in doc.descendants().filter(|n| is_tag(n, "list-style")) {- if let Some(name) = get_attr_local(&ls, "name") {- let is_ordered = ls+ for list_style in xml.descendants().filter(|n| is_tag(n, "list-style")) {+ if let Some(name) = attr(&list_style, "name") {+ let is_ordered = list_style.children()- .filter(|n| n.is_element()).any(|c| is_tag(&c, "list-level-style-number"));out.list_is_ordered.insert(name.to_string(), is_ordered);}@@ -174,413 +166,355 @@ fn harvest_styles_from_doc(doc: &XmlDoc, out: &mut OdtStylesInfo) {fn parse_text_properties(tp: &Node) -> TextStyleProps {let mut props = TextStyleProps::default();- if let Some(v) = get_attr_local(tp, "font-weight") {- if v.eq_ignore_ascii_case("bold") {- props.bold = true;- }+ if attr(tp, "font-weight").is_some_and(|v| v.eq_ignore_ascii_case("bold")) {+ props.bold = true;}- if let Some(v) = get_attr_local(tp, "font-style") {- if v.eq_ignore_ascii_case("italic") {- props.italic = true;- }+ if attr(tp, "font-style").is_some_and(|v| v.eq_ignore_ascii_case("italic")) {+ props.italic = true;}- if let Some(v) = get_attr_local(tp, "text-line-through-type")- .or_else(|| get_attr_local(tp, "text-line-through-style"))+ if attr(tp, "text-line-through-type")+ .or_else(|| attr(tp, "text-line-through-style"))+ .is_some_and(|v| v != "none"){- if v != "none" {- props.strike = true;- }+ props.strike = true;}- if let Some(v) = get_attr_local(tp, "text-position") {- let lv = v.to_ascii_lowercase();- if lv.contains("sup") || lv.contains("super") {+ if let Some(v) = attr(tp, "text-position") {+ let lower = v.to_ascii_lowercase();+ if lower.contains("sup") {props.sup = true;- } else if lv.contains("sub") {+ } else if lower.contains("sub") {props.sub = true;}}+ if let Some(font) = attr(tp, "font-name") {+ let lower = font.to_ascii_lowercase();+ if lower.contains("courier") || lower.contains("mono") {+ props.code = true;+ }+ }props}-fn read_meta<R: Read + Seek>(zip: &mut ZipArchive<R>) -> Option<DocumentMetadata> {- let text = read_zip_text(zip, "meta.xml")?;- let xml = XmlDoc::parse(strip_bom(&text)).ok()?;- let mut meta = DocumentMetadata::default();-- if let Some(title) = xml- .descendants()- .find(|n| is_tag(n, "title"))- .and_then(|n| n.text())- {- if !title.trim().is_empty() {- meta.title = Some(title.to_string());- }+/// Heading level from a style name like "Heading_20_2" or "Title".+fn parse_heading_level(style_name: &str) -> Option<u8> {+ let normalized = style_name.replace("_20_", " ").replace('_', " ");+ let lower = normalized.to_ascii_lowercase();+ if lower.contains("title") {+ return Some(1);}+ let tail = &lower[lower.find("heading")? + "heading".len()..];+ let digits: String = tail.chars().filter(|c| c.is_ascii_digit()).collect();+ digits.parse::<u8>().ok().map(|n| n.clamp(1, 6))+}- if let Some(author) = xml- .descendants()- .find(|n| is_tag(n, "creator"))- .and_then(|n| n.text())- .or_else(|| {- xml- .descendants()- .find(|n| is_tag(n, "initial-creator"))- .and_then(|n| n.text())- })- {- let trimmed = author.trim();- if !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("unknown") {- meta.author = Some(trimmed.to_string());+struct Parser<'a> {+ styles: &'a OdtStylesInfo,+ notes: Vec<Note>,+ comments: Vec<Comment>,+}++impl Parser<'_> {+ fn parse_blocks(&mut self, node: &Node) -> Vec<Block> {+ let mut blocks = Vec::new();++ for c in node.children().filter(|n| n.is_element()) {+ if is_tag(&c, "h") {+ self.push_paragraph(&c, &mut blocks);+ } else if is_tag(&c, "p") {+ if let Some(image) = image_from_paragraph(&c) {+ blocks.push(Block::Image(image));+ } else {+ self.push_paragraph(&c, &mut blocks);+ }+ } else if is_tag(&c, "list") {+ self.push_list(&c, &mut blocks);+ } else if is_tag(&c, "table") {+ blocks.push(Block::Table(self.parse_table(&c)));+ } else {+ blocks.extend(self.parse_blocks(&c));+ }}+ blocks}- if let Some(created) = xml- .descendants()- .find(|n| is_tag(n, "creation-date"))- .and_then(|n| n.text())- {- if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(created) {- meta.created = Some(DateTime::<Utc>::from(dt));+ fn push_paragraph(&mut self, node: &Node, blocks: &mut Vec<Block>) {+ let para = self.parse_paragraph(node);+ if has_visible_content(¶.inlines) {+ blocks.push(Block::Paragraph(para));}}- Some(meta)-}--fn is_tag(node: &Node, local: &str) -> bool {- node.is_element() && node.tag_name().name() == local-}--fn get_attr_local<'a>(node: &Node<'a, 'a>, local: &str) -> Option<&'a str> {- node- .attributes()- .find(|a| {- let name = a.name();- match name.rsplit_once(':') {- Some((_, l)) => l == local,- None => name == local,+ fn push_list(&mut self, list: &Node, blocks: &mut Vec<Block>) {+ // Writers wrap continuation sublists in a single-item shell list; unwrap+ // and attach them to the previous list's last item.+ let mut effective = *list;+ let mut inherited_style_name = attr(&effective, "style-name");+ let mut unwrapped = false;+ while let Some(inner) = unwrap_single_nested_list(&effective) {+ effective = inner;+ unwrapped = true;+ if inherited_style_name.is_none() {+ inherited_style_name = attr(&effective, "style-name");}- })- .map(|a| a.value())-}--fn child<'a>(node: &Node<'a, 'a>, local: &str) -> Option<Node<'a, 'a>> {- node- .children()- .find(|n| n.is_element() && n.tag_name().name() == local)-}--fn children<'a, 'b>(- node: &Node<'a, 'a>,- local: &'b str,-) -> impl Iterator<Item = Node<'a, 'a>> + use<'a, 'b> {- node- .children()- .filter(move |n| n.is_element() && n.tag_name().name() == local)-}+ }-fn parse_block_children_odt<R: Read + Seek>(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,- zip: &mut ZipArchive<R>,-) -> Vec<Block> {- let mut blocks: Vec<Block> = Vec::new();-- for child_n in node.children().filter(|n| n.is_element()) {- if is_tag(&child_n, "h") {- if let Some(p) = parse_paragraph(&child_n, styles, notes, comments) {- if paragraph_has_visible_content(&p) {- blocks.push(Block::Paragraph(p));- }- }- } else if is_tag(&child_n, "p") {- if let Some(img) = image_from_paragraph(&child_n, zip) {- blocks.push(Block::Image(img));- } else if let Some(p) = parse_paragraph(&child_n, styles, notes, comments) {- if paragraph_has_visible_content(&p) {- blocks.push(Block::Paragraph(p));- }- }- } else if is_tag(&child_n, "list") {- let mut effective = child_n;- let mut inherited_style_name = get_attr_local(&effective, "style-name");- let mut unwrapped = false;-- while let Some(inner) = unwrap_single_nested_list(&effective) {- effective = inner;- unwrapped = true;- if inherited_style_name.is_none() {- inherited_style_name = get_attr_local(&effective, "style-name");+ if is_heading_list(&effective) {+ for li in children(&effective, "list-item") {+ let headings: Vec<Node> = li.descendants().filter(|n| is_tag(n, "h")).collect();+ if let Some(h) = headings.first() {+ self.push_paragraph(h, blocks);}}+ return;+ }- if is_heading_list(&effective) {- for li in children(&effective, "list-item") {- if let Some(h) = li.descendants().find(|n| is_tag(n, "h")) {- if let Some(p) = parse_paragraph(&h, styles, notes, comments) {- if paragraph_has_visible_content(&p) {- blocks.push(Block::Paragraph(p));- }- }- }- }- } else if let Some(l) = parse_list_with_inherit(- &effective,- styles,- notes,- comments,- zip,- inherited_style_name,- ) {- if unwrapped {- if let Some(Block::List(prev)) = blocks.last_mut() {- if let Some(last_item) = prev.items.last_mut() {- last_item.blocks.push(Block::List(l));- continue;- }- }+ let parsed = self.parse_list(&effective, inherited_style_name);+ if unwrapped {+ if let Some(Block::List(prev)) = blocks.last_mut() {+ if let Some(last_item) = prev.items.last_mut() {+ last_item.blocks.push(Block::List(parsed));+ return;}- blocks.push(Block::List(l));- }- } else if is_tag(&child_n, "table") {- if let Some(t) = parse_table(&child_n, styles, notes, comments, zip) {- blocks.push(Block::Table(t));}- } else {- let mut inner = parse_block_children_odt(&child_n, styles, notes, comments, zip);- blocks.append(&mut inner);}+ blocks.push(Block::List(parsed));}- blocks-}+ fn parse_list(&mut self, node: &Node, inherited_style_name: Option<&str>) -> List {+ let style_name = attr(node, "style-name").or(inherited_style_name);+ let list_type = match style_name.and_then(|n| self.styles.list_is_ordered.get(n)) {+ Some(true) => ListType::Ordered,+ _ => ListType::Unordered,+ };-fn unwrap_single_nested_list<'a>(list: &Node<'a, 'a>) -> Option<Node<'a, 'a>> {- let mut li_iter = children(list, "list-item");- let first_li = li_iter.next()?;- if li_iter.next().is_some() {- return None;- }- let mut inner_lists = first_li.children().filter(|n| is_tag(n, "list"));- let inner = inner_lists.next()?;- if inner_lists.next().is_some() {- return None;+ let items = children(node, "list-item")+ .map(|li| ListItem {+ blocks: self.parse_blocks(&li),+ })+ .collect();+ List { items, list_type }}- Some(inner)-}-fn is_heading_list(list: &Node) -> bool {- let mut any = false;- for li in children(list, "list-item") {- any = true;- if !li.descendants().any(|n| is_tag(&n, "h")) {- return false;+ fn parse_table(&mut self, node: &Node) -> Table {+ let mut rows = Vec::new();+ for tr in children(node, "table-row") {+ let cells = children(&tr, "table-cell")+ .map(|tc| TableCell {+ blocks: self.parse_blocks(&tc),+ colspan: span_attr(&tc, "number-columns-spanned"),+ rowspan: span_attr(&tc, "number-rows-spanned"),+ })+ .collect();+ rows.push(TableRow {+ cells,+ kind: TableRowKind::Body,+ });}+ Table { rows }}- any-}-fn parse_paragraph(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,-) -> Option<Paragraph> {- let kind = paragraph_kind(node, styles);- let base = paragraph_text_props(node, styles);- let inlines = parse_inlines_with_base(node, styles, notes, comments, base);- Some(Paragraph { kind, inlines })-}--fn paragraph_kind(p: &Node, styles: &OdtStylesInfo) -> ParagraphKind {- if p.tag_name().name() == "h" {- if let Some(ol) = get_attr_local(p, "outline-level") {- if let Ok(v) = ol.parse::<u8>() {- return ParagraphKind::Heading(v.min(6));- }+ fn parse_paragraph(&mut self, node: &Node) -> Paragraph {+ let kind = self.paragraph_kind(node);+ let base = attr(node, "style-name")+ .and_then(|name| self.styles.paragraph_text_props.get(name))+ .copied()+ .unwrap_or_default();+ let inlines = self.parse_inlines(node);+ Paragraph {+ kind,+ inlines: apply_text_style(inlines, None, self.styles, base),}- return ParagraphKind::Heading(1);}- if let Some(style_name) = get_attr_local(p, "style-name") {- if let Some(lvl) = styles.paragraph_outline_level.get(style_name) {- return ParagraphKind::Heading((*lvl).min(6));+ fn paragraph_kind(&self, p: &Node) -> ParagraphKind {+ if p.tag_name().name() == "h" {+ let level = attr(p, "outline-level")+ .and_then(|v| v.parse::<u8>().ok())+ .unwrap_or(1);+ return ParagraphKind::Heading(level.clamp(1, 6));}- let name = styles- .paragraph_names- .get(style_name)- .map(|s| s.to_ascii_lowercase())- .unwrap_or_default();- if name.contains("quote") {- return ParagraphKind::Blockquote;+ if let Some(style_name) = attr(p, "style-name") {+ if let Some(level) = self.styles.paragraph_outline_level.get(style_name) {+ return ParagraphKind::Heading((*level).min(6));+ }+ if self.styles.paragraph_style_names.contains(style_name)+ && style_name.to_ascii_lowercase().contains("quote")+ {+ return ParagraphKind::Blockquote;+ }}+ ParagraphKind::Normal}- ParagraphKind::Normal-}+ fn parse_inlines(&mut self, node: &Node) -> Vec<Inline> {+ let mut out = Vec::new();-fn parse_odt_heading_level(style_name: &str) -> Option<u8> {- let normalized = style_name.replace("_20_", " ").replace('_', " ");- let lower = normalized.to_ascii_lowercase();- if lower.contains("title") {- return Some(1);- }+ for c in node.children() {+ if c.is_text() {+ if let Some(t) = c.text() {+ if !t.is_empty() {+ out.push(Inline::Text(t.to_string()));+ }+ }+ continue;+ }+ if !c.is_element() {+ continue;+ }- if let Some(idx) = lower.find("heading") {- let tail = &lower[idx + "heading".len()..];- let num: String = tail.chars().filter(|c| c.is_ascii_digit()).collect();- if let Ok(n) = num.parse::<u8>() {- return Some(n.clamp(1, 6));+ if is_tag(&c, "span") {+ let inner = self.parse_inlines(&c);+ let style_name = attr(&c, "style-name");+ out.extend(apply_text_style(+ inner,+ style_name,+ self.styles,+ TextStyleProps::default(),+ ));+ } else if is_tag(&c, "a") {+ let link_children = self.parse_inlines(&c);+ match attr(&c, "href") {+ Some(href) => out.push(Inline::Link {+ href: href.to_string(),+ children: link_children,+ }),+ None => out.extend(link_children),+ }+ } else if is_tag(&c, "line-break") {+ out.push(Inline::LineBreak);+ } else if is_tag(&c, "s") {+ // clamped so a malformed count cannot force a huge allocation+ let count = attr(&c, "c")+ .and_then(|v| v.parse::<usize>().ok())+ .unwrap_or(1)+ .min(1000);+ out.push(Inline::Text(" ".repeat(count)));+ } else if is_tag(&c, "tab") {+ out.push(Inline::Text("\t".to_string()));+ } else if is_tag(&c, "bookmark-start") {+ if let Some(name) = attr(&c, "name") {+ out.push(Inline::Bookmark(BookmarkId(name.to_string())));+ }+ } else if is_tag(&c, "note") {+ out.push(self.parse_note(&c));+ } else if is_tag(&c, "annotation") {+ out.push(self.parse_annotation(&c));+ } else {+ out.extend(self.parse_inlines(&c));+ }}+ out}- None-}-fn paragraph_text_props(node: &Node, styles: &OdtStylesInfo) -> TextStyleProps {- if let Some(style_name) = get_attr_local(node, "style-name") {- if let Some(p) = styles.paragraph_text_props.get(style_name) {- return *p;- }- }- TextStyleProps::default()-}+ fn parse_note(&mut self, node: &Node) -> Inline {+ let kind = match attr(node, "note-class") {+ Some("endnote") => NoteKind::Endnote,+ _ => NoteKind::Footnote,+ };+ let id = attr(node, "id")+ .map(|s| s.to_string())+ .unwrap_or_else(|| format!("odt-note-{}", self.notes.len() + 1));-fn parse_inlines(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,-) -> Vec<Inline> {- let mut out: Vec<Inline> = Vec::new();+ let blocks = child(node, "note-body")+ .map(|body| self.parse_note_body(&body))+ .unwrap_or_default();+ self.notes.push(Note {+ id: NoteId(id.clone()),+ kind,+ blocks,+ });- for c in node.children() {- if c.is_text() {- if let Some(t) = c.text() {- if !t.is_empty() {- out.push(Inline::Text(t.to_string()));- }- }- continue;- }- if !c.is_element() {- continue;+ match kind {+ NoteKind::Footnote => Inline::FootnoteRef(NoteId(id)),+ NoteKind::Endnote => Inline::EndnoteRef(NoteId(id)),}+ }- if is_tag(&c, "span") {- let mut inner = parse_inlines(&c, styles, notes, comments);- let sname = get_attr_local(&c, "style-name").map(|s| s.to_string());- inner = apply_text_style_wrappers(inner, sname.as_deref(), styles, TextStyleProps::default());- out.extend(inner);- } else if is_tag(&c, "a") {- if let Some(href) = get_attr_local(&c, "href") {- let children = parse_inlines(&c, styles, notes, comments);- out.push(Inline::Link {- href: href.to_string(),- children,- });- } else {- out.extend(parse_inlines(&c, styles, notes, comments));- }- } else if is_tag(&c, "line-break") {- out.push(Inline::LineBreak);- } else if is_tag(&c, "s") {- let count = get_attr_local(&c, "c")- .and_then(|v| v.parse::<usize>().ok())- .unwrap_or(1);- out.push(Inline::Text(" ".repeat(count)));- } else if is_tag(&c, "tab") {- out.push(Inline::Text("\t".to_string()));- } else if is_tag(&c, "bookmark-start") {- if let Some(name) = get_attr_local(&c, "name") {- out.push(Inline::Bookmark(BookmarkId(name.to_string())));- }- } else if is_tag(&c, "note") {- let kind = match get_attr_local(&c, "note-class") {- Some("endnote") => NoteKind::Endnote,- _ => NoteKind::Footnote,- };- let id = get_attr_local(&c, "id")- .map(|s| s.to_string())- .unwrap_or_else(|| format!("odt-note-{}", notes.len() + 1));- let body = child(&c, "note-body");- let mut blocks: Vec<Block> = Vec::new();- if let Some(b) = body {- blocks = parse_note_body_blocks(&b, styles, notes, comments);- }- notes.push(Note {- id: NoteId(id.clone()),- kind,- blocks,- });- match kind {- NoteKind::Footnote => out.push(Inline::FootnoteRef(NoteId(id))),- NoteKind::Endnote => out.push(Inline::EndnoteRef(NoteId(id))),+ fn parse_note_body(&mut self, node: &Node) -> Vec<Block> {+ let mut blocks = Vec::new();+ let paragraphs: Vec<Node> = node+ .children()+ .filter(|n| is_tag(n, "p") || is_tag(n, "h"))+ .collect();+ for p in paragraphs {+ let para = self.parse_paragraph(&p);+ if has_visible_content(¶.inlines) {+ blocks.push(Block::Paragraph(para));}- } else if is_tag(&c, "annotation") {- let cid = format!("odt-comment-{}", comments.len() + 1);- let mut author: Option<String> = None;- let mut initials: Option<String> = None;+ }+ blocks+ }- if let Some(a) = c+ fn parse_annotation(&mut self, node: &Node) -> Inline {+ let id = format!("odt-comment-{}", self.comments.len() + 1);+ let descendant_text = |local: &str| {+ node.descendants()- .find(|n| is_tag(n, "creator"))+ .find(|n| is_tag(n, local)).and_then(|n| n.text())- {- if !a.trim().is_empty() {- author = Some(a.to_string());- }- }- if let Some(init) = c- .descendants()- .find(|n| is_tag(n, "initials"))- .and_then(|n| n.text())- {- if !init.trim().is_empty() {- initials = Some(init.to_string());- }- }+ .map(str::trim)+ .filter(|t| !t.is_empty())+ .map(str::to_string)+ };+ let author = descendant_text("creator");+ let initials = descendant_text("initials");- let mut cblocks: Vec<Block> = Vec::new();- for p in c.children().filter(|n| is_tag(n, "p")) {- let inl = parse_inlines(&p, styles, notes, comments);- if !inl.is_empty() {- cblocks.push(Block::Paragraph(Paragraph {- kind: ParagraphKind::Normal,- inlines: inl,- }));- }+ let mut blocks = Vec::new();+ let paragraphs: Vec<Node> = node.children().filter(|n| is_tag(n, "p")).collect();+ for p in paragraphs {+ let inlines = self.parse_inlines(&p);+ if !inlines.is_empty() {+ blocks.push(Block::Paragraph(Paragraph {+ kind: ParagraphKind::Normal,+ inlines,+ }));}- comments.push(Comment {- id: CommentId(cid.clone()),- author_name: author,- author_initials: initials,- blocks: cblocks,- });- out.push(Inline::CommentRef(CommentId(cid)));- } else {- out.extend(parse_inlines(&c, styles, notes, comments));}++ self.comments.push(Comment {+ id: CommentId(id.clone()),+ author_name: author,+ author_initials: initials,+ blocks,+ });+ Inline::CommentRef(CommentId(id))}+}- out+fn span_attr(node: &Node, local: &str) -> NonZeroU32 {+ attr(node, local)+ .and_then(|v| v.parse::<u32>().ok())+ .and_then(NonZeroU32::new)+ .unwrap_or(NonZeroU32::MIN)}-fn parse_inlines_with_base(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,- base: TextStyleProps,-) -> Vec<Inline> {- let mut inlines = parse_inlines(node, styles, notes, comments);- inlines = apply_text_style_wrappers(inlines, None, styles, base);- inlines+fn unwrap_single_nested_list<'a>(list: &Node<'a, 'a>) -> Option<Node<'a, 'a>> {+ let mut items = children(list, "list-item");+ let first = items.next()?;+ if items.next().is_some() {+ return None;+ }+ let mut inner_lists = first.children().filter(|n| is_tag(n, "list"));+ let inner = inner_lists.next()?;+ if inner_lists.next().is_some() {+ return None;+ }+ Some(inner)+}++fn is_heading_list(list: &Node) -> bool {+ let mut any = false;+ for li in children(list, "list-item") {+ any = true;+ if !li.descendants().any(|n| is_tag(&n, "h")) {+ return false;+ }+ }+ any}-fn apply_text_style_wrappers(+fn apply_text_style(mut inlines: Vec<Inline>,style_name: Option<&str>,styles: &OdtStylesInfo,@@ -588,25 +522,16 @@ fn apply_text_style_wrappers() -> Vec<Inline> {let mut props = base;if let Some(name) = style_name {- let lower = name.to_ascii_lowercase();- let mut sprops = styles.text_props.get(name).copied().unwrap_or_default();- if lower.contains("code")- || styles- .text_font_name- .get(name)- .map(|f| {- f.to_ascii_lowercase().contains("courier") || f.to_ascii_lowercase().contains("mono")- })- .unwrap_or(false)- {- sprops.code = true;+ let mut style_props = styles.text_props.get(name).copied().unwrap_or_default();+ if name.to_ascii_lowercase().contains("code") {+ style_props.code = true;}- props.bold |= sprops.bold;- props.italic |= sprops.italic;- props.strike |= sprops.strike;- props.sup |= sprops.sup;- props.sub |= sprops.sub;- props.code |= sprops.code;+ props.bold |= style_props.bold;+ props.italic |= style_props.italic;+ props.strike |= style_props.strike;+ props.sup |= style_props.sup;+ props.sub |= style_props.sub;+ props.code |= style_props.code;}if props.code {@@ -640,125 +565,50 @@ fn apply_text_style_wrappers(inlines}-fn parse_note_body_blocks(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,-) -> Vec<Block> {- let mut blocks = Vec::new();- for p in node.children().filter(|n| is_tag(n, "p") || is_tag(n, "h")) {- let kind = paragraph_kind(&p, styles);- let base = paragraph_text_props(&p, styles);- let inl = parse_inlines_with_base(&p, styles, notes, comments, base);- if inlines_have_visible_content(&inl) {- blocks.push(Block::Paragraph(Paragraph { kind, inlines: inl }));- }- }- blocks-}--fn paragraph_has_visible_content(p: &Paragraph) -> bool {- inlines_have_visible_content(&p.inlines)-}--fn inlines_have_visible_content(inlines: &[Inline]) -> bool {- inlines.iter().any(inline_is_visible)-}--fn inline_is_visible(i: &Inline) -> bool {- match i {- Inline::Text(t) => !t.trim().is_empty(),- Inline::LineBreak => false,- Inline::Link { children, .. } => inlines_have_visible_content(children),- Inline::Strong(c) | Inline::Em(c) | Inline::Del(c) | Inline::Sup(c) | Inline::Sub(c) => {- inlines_have_visible_content(c)- }- Inline::Code(c) => !c.trim().is_empty(),- Inline::FootnoteRef(_) | Inline::EndnoteRef(_) | Inline::CommentRef(_) => true,- Inline::Bookmark(_) => false,- }-}--fn parse_list_with_inherit<R: Read + Seek>(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,- zip: &mut ZipArchive<R>,- inherit_style_name: Option<&str>,-) -> Option<List> {- let style_name = get_attr_local(node, "style-name").or(inherit_style_name);- let list_type = match style_name- .and_then(|n| styles.list_is_ordered.get(n))- .copied()- {- Some(true) => ListType::Ordered,- Some(false) => ListType::Unordered,- None => ListType::Unordered,- };-- let mut items: Vec<ListItem> = Vec::new();- for it in children(node, "list-item") {- let mut blocks = Vec::new();- let mut inner = parse_block_children_odt(&it, styles, notes, comments, zip);- blocks.append(&mut inner);- items.push(ListItem { blocks });- }- Some(List { items, list_type })-}--fn parse_table<R: Read + Seek>(- node: &Node,- styles: &OdtStylesInfo,- notes: &mut Vec<Note>,- comments: &mut Vec<Comment>,- zip: &mut ZipArchive<R>,-) -> Option<Table> {- let mut rows: Vec<TableRow> = Vec::new();- for tr in children(node, "table-row") {- let mut cells: Vec<TableCell> = Vec::new();- for tc in children(&tr, "table-cell") {- let mut blocks = parse_block_children_odt(&tc, styles, notes, comments, zip);- let colspan = get_attr_local(&tc, "number-columns-spanned")- .and_then(|v| v.parse::<u32>().ok())- .and_then(NonZeroU32::new)- .unwrap_or_else(|| NonZeroU32::new(1).unwrap());- let rowspan = get_attr_local(&tc, "number-rows-spanned")- .and_then(|v| v.parse::<u32>().ok())- .and_then(NonZeroU32::new)- .unwrap_or_else(|| NonZeroU32::new(1).unwrap());- cells.push(TableCell {- blocks: std::mem::take(&mut blocks),- colspan,- rowspan,- });- }- rows.push(TableRow {- cells,- kind: TableRowKind::Body,- });- }- Some(Table { rows })-}--fn image_from_paragraph<R: Read + Seek>(p: &Node, zip: &mut ZipArchive<R>) -> Option<Image> {- let img = p.descendants().find(|n| is_tag(n, "image"))?;- let href = get_attr_local(&img, "href")?;- image_from_href(href, zip, None)-}--fn image_from_href<R: Read + Seek>(- href: &str,- _zip: &mut ZipArchive<R>,- alt: Option<String>,-) -> Option<Image> {- // only include external images (http/https URLs)+fn image_from_paragraph(p: &Node) -> Option<Image> {+ let image = p.descendants().find(|n| is_tag(n, "image"))?;+ let href = attr(&image, "href")?;+ // only external images are representable in the outputif href.starts_with("http://") || href.starts_with("https://") {- return Some(Image {+ Some(Image {src: href.to_string(),- alt,- });+ alt: None,+ })+ } else {+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ #[test]+ fn huge_space_count_is_clamped() {+ let content = r#"<?xml version="1.0"?>+<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">+<office:body><office:text><text:p>a<text:s text:c="4000000000"/>b</text:p></office:text></office:body>+</office:document-content>"#;+ let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));+ zip+ .start_file("content.xml", zip::write::SimpleFileOptions::default())+ .unwrap();+ zip.write_all(content.as_bytes()).unwrap();+ let data = zip.finish().unwrap().into_inner();++ let document = OdtProvider::new().parse_buffer(&data).unwrap();+ let Block::Paragraph(p) = &document.blocks[0] else {+ panic!("expected paragraph");+ };+ let text: String = p+ .inlines+ .iter()+ .map(|i| match i {+ Inline::Text(t) => t.as_str(),+ _ => "",+ })+ .collect();+ assert_eq!(text.len(), "ab".len() + 1000);}- None}diff --git a/apps/api/native/src/document/providers/rtf.rs b/apps/api/native/src/document/providers/rtf.rsindex 5a49d20be..77d791563 100644--- a/apps/api/native/src/document/providers/rtf.rs+++ b/apps/api/native/src/document/providers/rtf.rs@@ -1,6 +1,11 @@+//! RTF provider. Tokenizes the RTF control stream and decodes 8-bit text+//! through the code page the document declares with \ansicpg.++use crate::document::encoding::encoding_for_codepage;use crate::document::model::*;use crate::document::providers::DocumentProvider;use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};+use encoding_rs::{Encoding, WINDOWS_1252};use std::error::Error;use std::num::NonZeroU32;@@ -14,8 +19,9 @@ impl RtfProvider {impl DocumentProvider for RtfProvider {fn parse_buffer(&self, data: &[u8]) -> Result<Document, Box<dyn Error + Send + Sync>> {- let metadata = extract_metadata_from_info(data).unwrap_or_default();- let blocks = parse_rtf_body_to_blocks(data);+ let encoding = detect_encoding(data);+ let metadata = extract_metadata(data, encoding);+ let blocks = parse_body(data, encoding);Ok(Document {blocks,@@ -30,101 +36,194 @@ impl DocumentProvider for RtfProvider {}}-fn extract_metadata_from_info(src: &[u8]) -> Option<DocumentMetadata> {- let start = find_group_start(src, b"{\\info")?;- let end = find_matching_brace(src, start)?;- let info = &src[start..end];-- let mut meta = DocumentMetadata::default();-- if let Some(author) = extract_simple_text_dest(info, br"{\author") {- if !author.eq_ignore_ascii_case("unknown") {- meta.author = Some(author);+/// Code page declared by the first \ansicpg control word. Token-based so+/// escaped literals like "\\ansicpg" in body text cannot match.+fn detect_encoding(src: &[u8]) -> &'static Encoding {+ for token in Tokens::new(src) {+ if let Token::Control("ansicpg", Some(codepage)) = token {+ return u16::try_from(codepage)+ .ok()+ .and_then(encoding_for_codepage)+ .unwrap_or(WINDOWS_1252);}}+ WINDOWS_1252+}- if let Some(title) = extract_simple_text_dest(info, br"{\title") {- if !title.trim().is_empty() {- meta.title = Some(title);- }- }+#[derive(Debug, PartialEq)]+enum Token<'a> {+ Open,+ Close,+ Control(&'a str, Option<i32>),+ Symbol(u8),+ Hex(u8),+ Byte(u8),+}- if let Some(created) = extract_creatim(info) {- meta.created = Some(created);- }+struct Tokens<'a> {+ src: &'a [u8],+ pos: usize,+}- Some(meta)+impl<'a> Tokens<'a> {+ fn new(src: &'a [u8]) -> Self {+ Self { src, pos: 0 }+ }}-fn find_group_start(buf: &[u8], needle: &[u8]) -> Option<usize> {- buf.windows(needle.len()).position(|w| w == needle)+impl<'a> Iterator for Tokens<'a> {+ type Item = Token<'a>;++ fn next(&mut self) -> Option<Token<'a>> {+ loop {+ let b = *self.src.get(self.pos)?;+ self.pos += 1;+ match b {+ b'\r' | b'\n' => continue,+ b'{' => return Some(Token::Open),+ b'}' => return Some(Token::Close),+ b'\\' => return self.next_after_backslash(),+ b => return Some(Token::Byte(b)),+ }+ }+ }}-fn find_matching_brace(buf: &[u8], start: usize) -> Option<usize> {- let mut depth = 0usize;- for (i, &b) in buf[start..].iter().enumerate() {+impl<'a> Tokens<'a> {+ fn next_after_backslash(&mut self) -> Option<Token<'a>> {+ let b = *self.src.get(self.pos)?;+ self.pos += 1;match b {- b'{' => depth += 1,- b'}' => {- depth -= 1;- if depth == 0 {- return Some(start + i + 1);+ b'\'' => {+ let hi = self.src.get(self.pos).copied().and_then(hex_val);+ let lo = self.src.get(self.pos + 1).copied().and_then(hex_val);+ match (hi, lo) {+ (Some(hi), Some(lo)) => {+ self.pos += 2;+ Some(Token::Hex((hi << 4) | lo))+ }+ // malformed escape; drop it and keep tokenizing+ _ => Some(Token::Symbol(b'\'')),}}- _ => {}+ b'a'..=b'z' | b'A'..=b'Z' => {+ let start = self.pos - 1;+ while self.src.get(self.pos).is_some_and(u8::is_ascii_alphabetic) {+ self.pos += 1;+ }+ let word = std::str::from_utf8(&self.src[start..self.pos]).ok()?;++ let mut value = None;+ let negative = self.src.get(self.pos) == Some(&b'-');+ let num_start = self.pos + negative as usize;+ let mut num_end = num_start;+ while self.src.get(num_end).is_some_and(u8::is_ascii_digit) {+ num_end += 1;+ }+ if num_end > num_start {+ // consume the digit run even when it overflows i32, so malformed+ // parameters do not leak digits into the text+ self.pos = num_end;+ if let Some(n) = std::str::from_utf8(&self.src[num_start..num_end])+ .ok()+ .and_then(|s| s.parse::<i32>().ok())+ {+ value = Some(if negative { -n } else { n });+ }+ }+ if self.src.get(self.pos) == Some(&b' ') {+ self.pos += 1;+ }+ Some(Token::Control(word, value))+ }+ b => {+ if b == b'*' && self.src.get(self.pos) == Some(&b' ') {+ self.pos += 1;+ }+ Some(Token::Symbol(b))+ }}}- None}-fn extract_simple_text_dest(buf: &[u8], start_tag: &[u8]) -> Option<String> {- let s = find_group_start(buf, start_tag)?;- let e = find_matching_brace(buf, s)?;- let mut out = String::new();- for &b in &buf[s + start_tag.len()..e - 1] {- push_byte_as_text(b, &mut out);- }- if out.trim().is_empty() {- None- } else {- Some(out.trim().to_string())+/// Fallback byte count declared by \uc. Kept as declared: skipping consumes+/// at most one byte per input token, so it is bounded by the input length.+fn uc_count(value: Option<i32>) -> usize {+ value.unwrap_or(1).max(0) as usize+}++fn hex_val(b: u8) -> Option<u8> {+ match b {+ b'0'..=b'9' => Some(b - b'0'),+ b'a'..=b'f' => Some(10 + b - b'a'),+ b'A'..=b'F' => Some(10 + b - b'A'),+ _ => None,}}-fn extract_creatim(buf: &[u8]) -> Option<DateTime<Utc>> {- let s = find_group_start(buf, br"{\creatim")?;- let e = find_matching_brace(buf, s)?;- let g = &buf[s..e];-- let mut yr: Option<i32> = None;- let mut mo: Option<u32> = None;- let mut dy: Option<u32> = None;- let mut hr: Option<u32> = None;- let mut mi: Option<u32> = None;-- let mut i = 0usize;- while i < g.len() {- if g[i] == b'\\' {- if let Some((word, val, ni)) = read_control_word(g, i + 1) {- match word.as_str() {- "yr" => yr = val,- "mo" => mo = val.map(|v| v as u32),- "dy" => dy = val.map(|v| v as u32),- "hr" => hr = val.map(|v| v as u32),- "min" => mi = val.map(|v| v as u32),- _ => {}- }- i = ni;- continue;+/// Accumulates text, buffering raw bytes so multi-byte code pages decode+/// across adjacent bytes.+struct TextAccum {+ encoding: &'static Encoding,+ pending: Vec<u8>,+ text: String,+}++impl TextAccum {+ fn new(encoding: &'static Encoding) -> Self {+ Self {+ encoding,+ pending: Vec::new(),+ text: String::new(),+ }+ }++ fn push_byte(&mut self, b: u8) {+ self.pending.push(b);+ }++ fn push_char(&mut self, c: char) {+ self.flush_pending();+ self.text.push(c);+ }++ fn flush_pending(&mut self) {+ if self.pending.is_empty() {+ return;+ }+ let (decoded, _) = self.encoding.decode_without_bom_handling(&self.pending);+ for ch in decoded.chars() {+ if ch == '\t' || ch == '\u{00A0}' || ch as u32 >= 0x20 {+ self.text.push(ch);}}- i += 1;+ self.pending.clear();}- let date = NaiveDate::from_ymd_opt(yr?, mo?, dy?)?;- let time = chrono::NaiveTime::from_hms_opt(hr.unwrap_or(0), mi.unwrap_or(0), 0)?;- let dt = NaiveDateTime::new(date, time);- Some(DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc))+ fn take(&mut self) -> String {+ self.flush_pending();+ std::mem::take(&mut self.text)+ }++ fn is_empty(&mut self) -> bool {+ self.flush_pending();+ self.text.is_empty()+ }+}++#[derive(Clone, Default)]+struct CharState {+ bold: bool,+ italic: bool,+ strike: bool,+ sup: bool,+ sub: bool,+}++struct Group {+ saved: CharState,+ skip: bool,+ name_seen: bool,}#[derive(Default)]@@ -148,12 +247,11 @@ impl TableBuilder {if self.current_cell_blocks.is_empty() {return;}- let cell = TableCell {+ self.current_row.push(TableCell {blocks: std::mem::take(&mut self.current_cell_blocks),- colspan: NonZeroU32::new(1).unwrap(),- rowspan: NonZeroU32::new(1).unwrap(),- };- self.current_row.push(cell);+ colspan: NonZeroU32::MIN,+ rowspan: NonZeroU32::MIN,+ });}fn finish_row(&mut self) {@@ -161,11 +259,10 @@ impl TableBuilder {if self.current_row.is_empty() {return;}- let row = TableRow {+ self.rows.push(TableRow {cells: std::mem::take(&mut self.current_row),kind: TableRowKind::Body,- };- self.rows.push(row);+ });}fn finalize(mut self) -> Option<Block> {@@ -178,587 +275,552 @@ impl TableBuilder {}}-fn push_block_target(- block: Block,- blocks: &mut Vec<Block>,- table: &mut Option<TableBuilder>,+const SKIP_DESTS: &[&str] = &[+ "fonttbl",+ "colortbl",+ "stylesheet",+ "listtable",+ "listoverridetable",+ "themedata",+ "latentstyles",+ "rsidtbl",+ "xmlnstbl",+ "mmathPr",+ "wgrffmtfilter",+ "datastore",+ "filetbl",+ "colorschememapping",+ "pnseclvl1",+ "pnseclvl2",+ "pnseclvl3",+ "pnseclvl4",+ "pnseclvl5",+ "pnseclvl6",+ "pnseclvl7",+ "pnseclvl8",+ "pnseclvl9",+ "pict",+ "object",+ "info",+];++struct BodyParser {+ state: CharState,+ stack: Vec<Group>,+ blocks: Vec<Block>,+ inlines: Vec<Inline>,+ text: TextAccum,+ table: Option<TableBuilder>,in_table_cell: bool,-) {- if in_table_cell {- if let Some(builder) = table.as_mut() {- builder.push_block(block);- } else {- blocks.push(block);- }- } else {- if let Some(builder) = table.take() {- if let Some(table_block) = builder.finalize() {- blocks.push(table_block);- }- }- blocks.push(block);- }+ uc_skip: usize,+ pending_uc_skip: usize,}-fn flush_table(blocks: &mut Vec<Block>, table: &mut Option<TableBuilder>) {- if let Some(builder) = table.take() {- if let Some(block) = builder.finalize() {- blocks.push(block);- }- }-}+fn parse_body(src: &[u8], encoding: &'static Encoding) -> Vec<Block> {+ let mut p = BodyParser {+ state: CharState::default(),+ stack: Vec::new(),+ blocks: Vec::new(),+ inlines: Vec::new(),+ text: TextAccum::new(encoding),+ table: None,+ in_table_cell: false,+ uc_skip: 1,+ pending_uc_skip: 0,+ };-fn parse_rtf_body_to_blocks(src: &[u8]) -> Vec<Block> {- let mut p = 0usize;- let n = src.len();-- #[derive(Clone, Default, Debug, PartialEq, Eq)]- struct State {- bold: bool,- italic: bool,- strike: bool,- sup: bool,- sub: bool,- }-- #[derive(Clone)]- struct Group {- saved: State,- skip: bool,- name_seen: bool,- }-- let mut state = State::default();- let mut stack: Vec<Group> = Vec::new();- let mut blocks: Vec<Block> = Vec::new();- let mut cur_inlines: Vec<Inline> = Vec::new();- let mut text_buf = String::new();- let mut table_builder: Option<TableBuilder> = None;- let mut in_table_cell = false;- let mut uc_skip: usize = 1;- let mut pending_uc_skip: usize = 0;-- const SKIP_DESTS: &[&str] = &[- "fonttbl",- "colortbl",- "stylesheet",- "listtable",- "listoverridetable",- "themedata",- "latentstyles",- "rsidtbl",- "xmlnstbl",- "mmathPr",- "wgrffmtfilter",- "datastore",- "filetbl",- "colorschememapping",- "pnseclvl1",- "pnseclvl2",- "pnseclvl3",- "pnseclvl4",- "pnseclvl5",- "pnseclvl6",- "pnseclvl7",- "pnseclvl8",- "pnseclvl9",- "pict",- "object",- "info",- ];-- fn style_wrap(mut node: Inline, st: &State) -> Inline {- if st.strike {- node = Inline::Del(vec![node]);- }- if st.italic {- node = Inline::Em(vec![node]);- }- if st.bold {- node = Inline::Strong(vec![node]);- }- if st.sup {- node = Inline::Sup(vec![node]);- } else if st.sub {- node = Inline::Sub(vec![node]);- }- node+ for token in Tokens::new(src) {+ p.handle_token(token);}- fn push_text_buf(text_buf: &mut String, cur: &mut Vec<Inline>, st: &State) {- if !text_buf.is_empty() {- let node = style_wrap(Inline::Text(text_buf.clone()), st);- cur.push(node);- text_buf.clear();- }+ if !p.text.is_empty() || !p.inlines.is_empty() {+ p.flush_paragraph();}+ p.flush_table();+ p.blocks+}- fn has_visible_content(inlines: &[Inline]) -> bool {- inlines.iter().any(|i| match i {- Inline::Text(t) => !t.trim().is_empty(),- Inline::LineBreak => false,- Inline::Link { children, .. } => has_visible_content(children),- Inline::Strong(c) | Inline::Em(c) | Inline::Del(c) | Inline::Sup(c) | Inline::Sub(c) => {- has_visible_content(c)- }- Inline::Code(t) => !t.trim().is_empty(),- Inline::FootnoteRef(_) | Inline::EndnoteRef(_) | Inline::CommentRef(_) => true,- Inline::Bookmark(_) => false,- })+impl BodyParser {+ fn skipping(&self) -> bool {+ self.stack.last().map(|g| g.skip).unwrap_or(false)}- fn flush_paragraph(- cur: &mut Vec<Inline>,- text_buf: &mut String,- blocks: &mut Vec<Block>,- table: &mut Option<TableBuilder>,- st: &State,- in_table_cell: bool,- ) {- push_text_buf(text_buf, cur, st);- if has_visible_content(cur) {- let block = Block::Paragraph(Paragraph {- kind: ParagraphKind::Normal,- inlines: std::mem::take(cur),- });- push_block_target(block, blocks, table, in_table_cell);- } else {- cur.clear();- if !in_table_cell {- flush_table(blocks, table);+ fn handle_token(&mut self, token: Token) {+ if self.pending_uc_skip > 0 {+ match token {+ Token::Byte(_) | Token::Hex(_) => {+ self.pending_uc_skip -= 1;+ return;+ }+ _ => self.pending_uc_skip = 0,}}- }- let flush_before_change = |text_buf: &mut String, cur: &mut Vec<Inline>, st: &State| {- push_text_buf(text_buf, cur, st);- };-- while p < n {- match src[p] {- b'{' => {- let inherited_skip = stack.last().map(|g| g.skip).unwrap_or(false);- stack.push(Group {- saved: state.clone(),+ match token {+ Token::Open => {+ let inherited_skip = self.skipping();+ self.stack.push(Group {+ saved: self.state.clone(),skip: inherited_skip,name_seen: false,});- p += 1;}- b'}' => {- if let Some(g) = stack.last() {- if !g.skip {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- }+ Token::Close => {+ if !self.skipping() {+ self.flush_text();}- if let Some(g) = stack.pop() {- state = g.saved;+ if let Some(group) = self.stack.pop() {+ self.state = group.saved;}- p += 1;}- b'\\' => {- if p + 1 >= n {- break;+ Token::Byte(b) | Token::Hex(b) => {+ if !self.skipping() {+ self.text.push_byte(b);}- let next = src[p + 1];-- if next == b'\\' || next == b'{' || next == b'}' {- if !stack.last().map(|g| g.skip).unwrap_or(false) {- text_buf.push(next as char);+ }+ Token::Symbol(b'*') => {+ if let Some(group) = self.stack.last_mut() {+ if !group.name_seen {+ group.name_seen = true;+ group.skip = true;}- p += 2;- continue;}+ }+ Token::Symbol(b @ (b'\\' | b'{' | b'}')) => {+ if !self.skipping() {+ self.text.push_byte(b);+ }+ }+ Token::Symbol(b'~') => {+ if !self.skipping() {+ self.text.push_char('\u{00A0}');+ }+ }+ Token::Symbol(b'-') => {+ if !self.skipping() {+ self.text.push_char('\u{00AD}');+ }+ }+ Token::Symbol(_) => {}+ Token::Control(word, value) => self.handle_control(word, value),+ }+ }- if next == b'\'' {- if p + 3 < n {- let h1 = src[p + 2];- let h2 = src[p + 3];- if !stack.last().map(|g| g.skip).unwrap_or(false) {- if let (Some(a), Some(b)) = (hex_val(h1), hex_val(h2)) {- let byte = (a << 4) | b;- push_byte_as_text(byte, &mut text_buf);- }- }- p += 4;- continue;- } else {- break;- }+ fn handle_control(&mut self, word: &str, value: Option<i32>) {+ if let Some(group) = self.stack.last_mut() {+ if !group.name_seen {+ group.name_seen = true;+ if SKIP_DESTS.contains(&word) {+ group.skip = true;}+ }+ }- let skip = stack.last().map(|g| g.skip).unwrap_or(false);+ if self.skipping() {+ return;+ }+ if word == "par" {+ self.flush_paragraph();+ return;+ }- match next {- b'~' => {- if !skip {- text_buf.push('\u{00A0}');- } // non-breaking space- p += 2;- continue;+ let on = |value: Option<i32>| value.map(|v| v != 0).unwrap_or(true);+ match word {+ "rquote" => self.text.push_char('\u{2019}'),+ "lquote" => self.text.push_char('\u{2018}'),+ "rdblquote" => self.text.push_char('\u{201D}'),+ "ldblquote" => self.text.push_char('\u{201C}'),+ "emdash" => self.text.push_char('\u{2014}'),+ "endash" => self.text.push_char('\u{2013}'),+ "bullet" => self.text.push_char('\u{2022}'),+ "tab" => self.text.push_char('\t'),+ "line" => {+ self.flush_text();+ self.inlines.push(Inline::LineBreak);+ }+ "u" => {+ if let Some(mut code) = value {+ if code < 0 {+ code += 65536;}- b'-' => {- if !skip {- text_buf.push('\u{00AD}');- } // soft hyphen- p += 2;- continue;+ if let Some(ch) = char::from_u32(code as u32) {+ self.text.push_char(ch);}- _ => {}- }-- if starts_with_word(src, p + 1, b"rquote") {- if !skip {- text_buf.push('\u{2019}');- } // '- p = skip_word_and_space(src, p + 1);- continue;- }- if starts_with_word(src, p + 1, b"lquote") {- if !skip {- text_buf.push('\u{2018}');- } // '- p = skip_word_and_space(src, p + 1);- continue;- }- if starts_with_word(src, p + 1, b"rdblquote") {- if !skip {- text_buf.push('\u{201D}');- } // "- p = skip_word_and_space(src, p + 1);- continue;- }- if starts_with_word(src, p + 1, b"ldblquote") {- if !skip {- text_buf.push('\u{201C}');- } // "- p = skip_word_and_space(src, p + 1);- continue;- }- if starts_with_word(src, p + 1, b"emdash") {- if !skip {- text_buf.push('\u{2014}');- } // —- p = skip_word_and_space(src, p + 1);- continue;+ self.pending_uc_skip = self.uc_skip;}- if starts_with_word(src, p + 1, b"endash") {- if !skip {- text_buf.push('\u{2013}');- } // –- p = skip_word_and_space(src, p + 1);- continue;+ }+ "uc" => self.uc_skip = uc_count(value),+ "b" => {+ self.flush_text();+ self.state.bold = on(value);+ }+ "i" => {+ self.flush_text();+ self.state.italic = on(value);+ }+ "strike" | "striked" | "striked1" => {+ self.flush_text();+ self.state.strike = on(value);+ }+ "super" => {+ self.flush_text();+ self.state.sup = on(value);+ if self.state.sup {+ self.state.sub = false;}- if starts_with_word(src, p + 1, b"bullet") {- if !skip {- text_buf.push('\u{2022}');- } // •- p = skip_word_and_space(src, p + 1);- continue;+ }+ "sub" => {+ self.flush_text();+ self.state.sub = on(value);+ if self.state.sub {+ self.state.sup = false;}- if starts_with_word(src, p + 1, b"line") {- if !skip {- push_text_buf(&mut text_buf, &mut cur_inlines, &state);- cur_inlines.push(Inline::LineBreak);- }- p = skip_word_and_space(src, p + 1);- continue;+ }+ "nosupersub" => {+ self.flush_text();+ self.state.sup = false;+ self.state.sub = false;+ }+ "plain" => {+ self.flush_text();+ self.state = CharState::default();+ }+ "trowd" => {+ self.table.get_or_insert_with(TableBuilder::default).start_row();+ self.in_table_cell = false;+ }+ "intbl" => self.in_table_cell = true,+ "cell" => {+ self.in_table_cell = true;+ self.flush_paragraph();+ if let Some(table) = self.table.as_mut() {+ table.finish_cell();}- if starts_with_word(src, p + 1, b"tab") {- if !skip {- text_buf.push('\t');- }- p = skip_word_and_space(src, p + 1);- continue;+ self.in_table_cell = false;+ }+ "row" => {+ if let Some(table) = self.table.as_mut() {+ table.finish_row();}+ self.in_table_cell = false;+ }+ _ => {}+ }+ }- if let Some((word, val, new_p)) = read_control_word(src, p + 1) {- if let Some(g) = stack.last_mut() {- if !g.name_seen {- g.name_seen = true;- if word == "*" || SKIP_DESTS.contains(&word.as_str()) {- g.skip = true;- }- }- }-- let skipping = stack.last().map(|g| g.skip).unwrap_or(false);-- if !skipping {- match word.as_str() {- "trowd" => {- let builder = table_builder.get_or_insert_with(TableBuilder::default);- builder.start_row();- in_table_cell = false;- }- "intbl" => {- in_table_cell = true;- }- "cell" => {- flush_paragraph(- &mut cur_inlines,- &mut text_buf,- &mut blocks,- &mut table_builder,- &state,- true,- );- if let Some(builder) = table_builder.as_mut() {- builder.finish_cell();- }- in_table_cell = false;- }- "row" => {- if let Some(builder) = table_builder.as_mut() {- builder.finish_row();- }- in_table_cell = false;- }- "cellx" | "clvertalb" | "clvertalc" | "clvertalt" => {}- "b" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state.bold = val.map(|v| v != 0).unwrap_or(true);- }- "i" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state.italic = val.map(|v| v != 0).unwrap_or(true);- }- "strike" | "striked" | "striked1" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state.strike = val.map(|v| v != 0).unwrap_or(true);- }- "super" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state.sup = val.map(|v| v != 0).unwrap_or(true);- if state.sup {- state.sub = false;- }- }- "sub" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state.sub = val.map(|v| v != 0).unwrap_or(true);- if state.sub {- state.sup = false;- }- }- "nosupersub" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state.sup = false;- state.sub = false;- }- "plain" => {- flush_before_change(&mut text_buf, &mut cur_inlines, &state);- state = State::default();- }- "par" => {- flush_paragraph(- &mut cur_inlines,- &mut text_buf,- &mut blocks,- &mut table_builder,- &state,- in_table_cell,- );- }- "uc" => {- uc_skip = val.unwrap_or(1).max(0) as usize;- }- "u" => {- if let Some(mut num) = val {- if num < 0 {- num += 65536;- }- if let Some(ch) = std::char::from_u32(num as u32) {- text_buf.push(ch);- }- pending_uc_skip = uc_skip;- }- }- _ => {}- }- } else if word == "par" {- flush_paragraph(- &mut cur_inlines,- &mut text_buf,- &mut blocks,- &mut table_builder,- &state,- in_table_cell,- );- }+ fn flush_text(&mut self) {+ let text = self.text.take();+ if text.is_empty() {+ return;+ }+ let mut node = Inline::Text(text);+ if self.state.strike {+ node = Inline::Del(vec![node]);+ }+ if self.state.italic {+ node = Inline::Em(vec![node]);+ }+ if self.state.bold {+ node = Inline::Strong(vec![node]);+ }+ if self.state.sup {+ node = Inline::Sup(vec![node]);+ } else if self.state.sub {+ node = Inline::Sub(vec![node]);+ }+ self.inlines.push(node);+ }- let mut final_p = new_p;- if pending_uc_skip > 0 {- let mut k = 0usize;- while k < pending_uc_skip && final_p < n {- if matches!(src[final_p], b'\\' | b'{' | b'}') {- break;- }- final_p += 1;- k += 1;- }- pending_uc_skip = 0;- }- p = final_p;- continue;+ fn flush_paragraph(&mut self) {+ self.flush_text();+ if has_visible_content(&self.inlines) {+ let block = Block::Paragraph(Paragraph {+ kind: ParagraphKind::Normal,+ inlines: std::mem::take(&mut self.inlines),+ });+ if self.in_table_cell {+ if let Some(table) = self.table.as_mut() {+ table.push_block(block);+ } else {+ self.blocks.push(block);}- p += 1;+ } else {+ self.flush_table();+ self.blocks.push(block);}- b'\r' | b'\n' => {- p += 1;+ } else {+ self.inlines.clear();+ if !self.in_table_cell {+ self.flush_table();}- byte => {- if !stack.last().map(|g| g.skip).unwrap_or(false) {- if pending_uc_skip > 0 {- pending_uc_skip -= 1;- } else {- push_byte_as_text(byte, &mut text_buf);- }- }- p += 1;+ }+ }++ fn flush_table(&mut self) {+ if let Some(table) = self.table.take() {+ if let Some(block) = table.finalize() {+ self.blocks.push(block);}}}+}- if !text_buf.is_empty() || !cur_inlines.is_empty() {- flush_paragraph(- &mut cur_inlines,- &mut text_buf,- &mut blocks,- &mut table_builder,- &state,- in_table_cell,- );+fn extract_metadata(src: &[u8], encoding: &'static Encoding) -> DocumentMetadata {+ let mut metadata = DocumentMetadata::default();+ let Some(info) = find_group(src, b"{\\info") else {+ return metadata;+ };++ if let Some(author) = find_group(info, b"{\\author").and_then(|g| group_text(g, encoding)) {+ if !author.eq_ignore_ascii_case("unknown") {+ metadata.author = Some(author);+ }}+ if let Some(title) = find_group(info, b"{\\title").and_then(|g| group_text(g, encoding)) {+ metadata.title = Some(title);+ }+ metadata.created = find_group(info, b"{\\creatim").and_then(parse_timestamp);- flush_table(&mut blocks, &mut table_builder);+ metadata+}- blocks+fn find_group<'a>(buf: &'a [u8], start_tag: &[u8]) -> Option<&'a [u8]> {+ let start = buf.windows(start_tag.len()).position(|w| w == start_tag)?;+ let mut depth = 0usize;+ for (i, &b) in buf[start..].iter().enumerate() {+ match b {+ b'{' => depth += 1,+ b'}' => {+ depth -= 1;+ if depth == 0 {+ return Some(&buf[start..start + i + 1]);+ }+ }+ _ => {}+ }+ }+ None}-fn read_control_word(src: &[u8], mut i: usize) -> Option<(String, Option<i32>, usize)> {- if i >= src.len() {- return None;+/// Plain text of a destination group, flattening nested formatting groups+/// and ignoring \*-prefixed destinations.+fn group_text(group: &[u8], encoding: &'static Encoding) -> Option<String> {+ let mut accum = TextAccum::new(encoding);+ let mut depth = 0usize;+ let mut ignored_depth: Option<usize> = None;+ let mut just_opened = false;+ let mut pending_uc_skip = 0usize;+ let mut uc_skip = 1usize;++ for token in Tokens::new(group) {+ if just_opened {+ just_opened = false;+ if matches!(token, Token::Symbol(b'*')) && ignored_depth.is_none() {+ ignored_depth = Some(depth);+ continue;+ }+ }+ match token {+ Token::Open => {+ depth += 1;+ just_opened = true;+ continue;+ }+ Token::Close => {+ depth = depth.saturating_sub(1);+ if ignored_depth.is_some_and(|d| depth < d) {+ ignored_depth = None;+ }+ continue;+ }+ _ => {}+ }+ if ignored_depth.is_some() {+ continue;+ }+ if pending_uc_skip > 0 {+ match token {+ Token::Byte(_) | Token::Hex(_) => {+ pending_uc_skip -= 1;+ continue;+ }+ _ => pending_uc_skip = 0,+ }+ }+ match token {+ Token::Byte(b) | Token::Hex(b) => accum.push_byte(b),+ Token::Symbol(b @ (b'\\' | b'{' | b'}')) => accum.push_byte(b),+ Token::Control("u", Some(mut code)) => {+ if code < 0 {+ code += 65536;+ }+ if let Some(ch) = char::from_u32(code as u32) {+ accum.push_char(ch);+ }+ pending_uc_skip = uc_skip;+ }+ Token::Control("uc", value) => uc_skip = uc_count(value),+ _ => {}+ }}- if src[i] == b'*' {- i += 1;- if i < src.len() && src[i] == b' ' {- i += 1;+ let text = accum.take().trim().to_string();+ if text.is_empty() {+ None+ } else {+ Some(text)+ }+}++fn parse_timestamp(group: &[u8]) -> Option<DateTime<Utc>> {+ let mut yr = None;+ let mut mo = None;+ let mut dy = None;+ let mut hr = None;+ let mut mi = None;++ for token in Tokens::new(group) {+ if let Token::Control(word, value) = token {+ match word {+ "yr" => yr = value,+ "mo" => mo = value.map(|v| v as u32),+ "dy" => dy = value.map(|v| v as u32),+ "hr" => hr = value.map(|v| v as u32),+ "min" => mi = value.map(|v| v as u32),+ _ => {}+ }}- return Some(("*".to_string(), None, i));}- let start = i;- while i < src.len() && is_alpha(src[i]) {- i += 1;+ let date = NaiveDate::from_ymd_opt(yr?, mo?, dy?)?;+ let time = chrono::NaiveTime::from_hms_opt(hr.unwrap_or(0), mi.unwrap_or(0), 0)?;+ Some(DateTime::<Utc>::from_naive_utc_and_offset(+ NaiveDateTime::new(date, time),+ Utc,+ ))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::document::providers::DocumentProvider;++ fn paragraphs(data: &[u8]) -> Vec<String> {+ let document = RtfProvider::new().parse_buffer(data).unwrap();+ document+ .blocks+ .iter()+ .filter_map(|block| match block {+ Block::Paragraph(p) => Some(inline_text(&p.inlines)),+ _ => None,+ })+ .collect()+ }++ fn inline_text(inlines: &[Inline]) -> String {+ inlines+ .iter()+ .map(|inline| match inline {+ Inline::Text(t) => t.clone(),+ Inline::Strong(c) | Inline::Em(c) | Inline::Del(c) | Inline::Sup(c) | Inline::Sub(c) => {+ inline_text(c)+ }+ _ => String::new(),+ })+ .collect()}- if i == start {- return None;++ #[test]+ fn ansicpg1251_hex_escapes() {+ let rtf = b"{\\rtf1\\ansi\\ansicpg1251 \\'d3\\'ea\\'f0\\'e0\\'bf\\'ed\\'e0\\par}";+ assert_eq!(paragraphs(rtf), vec!["Україна"]);}- let word = String::from_utf8_lossy(&src[start..i]).to_string();- let mut sign = 1i32;- let mut val: Option<i32> = None;- if i < src.len() && (src[i] == b'-' || is_digit(src[i])) {- if src[i] == b'-' {- sign = -1;- i += 1;- }- let num_start = i;- while i < src.len() && is_digit(src[i]) {- i += 1;- }- if i > num_start {- let n = std::str::from_utf8(&src[num_start..i])- .ok()?- .parse::<i32>()- .ok()?;- val = Some(sign * n);- }+ #[test]+ fn default_cp1252_hex_escapes() {+ let rtf = b"{\\rtf1\\ansi Caf\\'e9 \\'93ok\\'94\\par}";+ assert_eq!(paragraphs(rtf), vec!["Café \u{201C}ok\u{201D}"]);}- if i < src.len() && src[i] == b' ' {- i += 1;+ #[test]+ fn unicode_escape_with_fallback() {+ let rtf = b"{\\rtf1\\ansi\\uc1 \\u1059?\\u1082?\\u1088? ok\\par}";+ assert_eq!(paragraphs(rtf), vec!["Укр ok"]);}- Some((word, val, i))-}+ #[test]+ fn shift_jis_double_byte_pairs() {+ let rtf = b"{\\rtf1\\ansi\\ansicpg932 \\'93\\'fa\\'96\\'7b\\par}";+ assert_eq!(paragraphs(rtf), vec!["日本"]);+ }-#[inline]-fn is_alpha(b: u8) -> bool {- b.is_ascii_uppercase() || b.is_ascii_lowercase()-}+ #[test]+ fn styles_and_tables_still_parse() {+ let rtf = b"{\\rtf1\\ansi {\\b Bold} and {\\i italic}\\par\\trowd\\intbl A\\cell B\\cell\\row\\par}";+ let document = RtfProvider::new().parse_buffer(rtf).unwrap();+ assert!(matches!(document.blocks[0], Block::Paragraph(_)));+ assert!(document+ .blocks+ .iter()+ .any(|b| matches!(b, Block::Table(t) if t.rows[0].cells.len() == 2)));+ }-#[inline]-fn is_digit(b: u8) -> bool {- b.is_ascii_digit()-}+ #[test]+ fn info_metadata_decodes_with_document_codepage() {+ let rtf = b"{\\rtf1\\ansi\\ansicpg1251{\\info{\\title \\'d3\\'ea\\'e0\\'e7}{\\author Iryna}{\\creatim\\yr2022\\mo6\\dy9\\hr15\\min24}}Body\\par}";+ let document = RtfProvider::new().parse_buffer(rtf).unwrap();+ assert_eq!(document.metadata.title.as_deref(), Some("Указ"));+ assert_eq!(document.metadata.author.as_deref(), Some("Iryna"));+ assert_eq!(+ document.metadata.created.unwrap().to_rfc3339(),+ "2022-06-09T15:24:00+00:00"+ );+ }-fn hex_val(b: u8) -> Option<u8> {- match b {- b'0'..=b'9' => Some(b - b'0'),- b'a'..=b'f' => Some(10 + (b - b'a')),- b'A'..=b'F' => Some(10 + (b - b'A')),- _ => None,+ #[test]+ fn metadata_keeps_text_of_nested_formatting_groups() {+ let rtf =+ b"{\\rtf1{\\info{\\title Some {\\b Bold} Title{\\*\\junk secret}}}Body\\par}";+ let document = RtfProvider::new().parse_buffer(rtf).unwrap();+ assert_eq!(document.metadata.title.as_deref(), Some("Some Bold Title"));}-}-fn push_byte_as_text(byte: u8, text_buf: &mut String) {- let ch = decode_cp1252(byte);- let cp = ch as u32;- if ch == '\t' || ch == '\u{00A0}' || cp >= 0x20 {- text_buf.push(ch);+ #[test]+ fn par_inside_ignored_destination_does_not_split_paragraphs() {+ let rtf = b"{\\rtf1\\ansi Hello{\\*\\junkdest gone\\par gone too} world\\par}";+ assert_eq!(paragraphs(rtf), vec!["Hello world"]);}-}-fn decode_cp1252(b: u8) -> char {- if b < 0x80 {- return b as char;+ #[test]+ fn malformed_hex_escape_does_not_truncate_document() {+ let rtf = b"{\\rtf1\\ansi before \\'zz after\\par}";+ assert_eq!(paragraphs(rtf), vec!["before zz after"]);}- match b {- 0x80 => '\u{20AC}', // €- 0x82 => '\u{201A}', // ‚- 0x83 => '\u{0192}', // ƒ- 0x84 => '\u{201E}', // „- 0x85 => '\u{2026}', // …- 0x86 => '\u{2020}', // †- 0x87 => '\u{2021}', // ‡- 0x88 => '\u{02C6}', // ˆ- 0x89 => '\u{2030}', // ‰- 0x8A => '\u{0160}', // Š- 0x8B => '\u{2039}', // ‹- 0x8C => '\u{0152}', // Œ- 0x8E => '\u{017D}', // Ž- 0x91 => '\u{2018}', // '- 0x92 => '\u{2019}', // '- 0x93 => '\u{201C}', // "- 0x94 => '\u{201D}', // "- 0x95 => '\u{2022}', // •- 0x96 => '\u{2013}', // –- 0x97 => '\u{2014}', // —- 0x98 => '\u{02DC}', // ˜- 0x99 => '\u{2122}', // ™- 0x9A => '\u{0161}', // š- 0x9B => '\u{203A}', // ›- 0x9C => '\u{0153}', // œ- 0x9E => '\u{017E}', // ž- 0x9F => '\u{0178}', // Ÿ- _ => b as char,++ #[test]+ fn escaped_ansicpg_literal_does_not_change_encoding() {+ let rtf = b"{\\rtf1\\ansi text \\\\ansicpg1251 \\'e9\\par}";+ assert_eq!(paragraphs(rtf), vec!["text \\ansicpg1251 é"]);}-}-fn starts_with_word(src: &[u8], i: usize, word: &[u8]) -> bool {- let end = i + word.len();- end <= src.len() && &src[i..end] == word-}+ #[test]+ fn overflowing_control_parameter_digits_do_not_leak() {+ let rtf = b"{\\rtf1\\ansi a\\u99999999999999x b\\par}";+ assert_eq!(paragraphs(rtf), vec!["ax b"]);+ }-fn skip_word_and_space(src: &[u8], mut i: usize) -> usize {- while i < src.len() && is_alpha(src[i]) {- i += 1;+ #[test]+ fn uc_above_eight_skips_declared_fallback_bytes() {+ let rtf = b"{\\rtf1\\ansi\\uc10\\u1059 abcdefghijkl\\par}";+ assert_eq!(paragraphs(rtf), vec!["Уkl"]);}- if i < src.len() && src[i] == b' ' {- i += 1;++ #[test]+ fn huge_uc_value_stays_bounded_by_input() {+ let rtf = b"{\\rtf1\\ansi\\uc2000000000\\u1059 abc\\par done\\par}";+ assert_eq!(paragraphs(rtf), vec!["У", "done"]);}- i}+++diff --git a/apps/api/native/src/document/xml.rs b/apps/api/native/src/document/xml.rsnew file mode 100644index 000000000..45ce1cec7--- /dev/null+++ b/apps/api/native/src/document/xml.rs@@ -0,0 +1,49 @@+//! Helpers shared by the zip+XML based providers (docx, odt).++use roxmltree::Node;+use std::io::{Read, Seek};+use zip::read::ZipArchive;++pub fn read_zip_text<R: Read + Seek>(zip: &mut ZipArchive<R>, path: &str) -> Option<String> {+ let mut file = zip.by_name(path).ok()?;+ let mut s = String::new();+ file.read_to_string(&mut s).ok()?;+ Some(s)+}++pub fn strip_bom(s: &str) -> &str {+ s.strip_prefix('\u{FEFF}').unwrap_or(s)+}++pub fn is_tag(node: &Node, local: &str) -> bool {+ node.is_element() && node.tag_name().name() == local+}++/// Attribute value matched by local name, ignoring the namespace prefix.+pub fn attr<'a>(node: &Node<'a, 'a>, local: &str) -> Option<&'a str> {+ node+ .attributes()+ .find(|a| {+ let name = a.name();+ match name.rsplit_once(':') {+ Some((_, l)) => l == local,+ None => name == local,+ }+ })+ .map(|a| a.value())+}++pub fn child<'a>(node: &Node<'a, 'a>, local: &str) -> Option<Node<'a, 'a>> {+ node+ .children()+ .find(|n| n.is_element() && n.tag_name().name() == local)+}++pub fn children<'a, 'b>(+ node: &Node<'a, 'a>,+ local: &'b str,+) -> impl Iterator<Item = Node<'a, 'a>> + use<'a, 'b> {+ node+ .children()+ .filter(move |n| n.is_element() && n.tag_name().name() == local)+}