diff --git a/crates/xlsx/src/drawing.rs b/crates/xlsx/src/drawing.rs index 56790940b..ea9363a83 100644 --- a/crates/xlsx/src/drawing.rs +++ b/crates/xlsx/src/drawing.rs @@ -272,7 +272,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option { } let fill = sp.child("solidFill").and_then(dml_color).unwrap_or_default(); let line = ln.and_then(|l| l.child("solidFill")).and_then(dml_color).unwrap_or_default(); - let text = obj.child("txBody").map(body_text).unwrap_or_default(); + let text = tb.map(|tb| if has_math { math_body_text(tb) } else { body_text(tb) }).unwrap_or_default(); let mut format = read_text_format(obj.child("txBody")); format.no_line = ln.is_some_and(|l| l.child("noFill").is_some()); let rotation = sp @@ -418,6 +418,55 @@ fn body_text(tb: &El) -> String { tb.kids("p").map(|p| p.kids("r").filter_map(|r| r.child("t")).map(|t| t.text.as_str()).collect::()).collect::>().join("\n") } +/// A rejected Office Math box still needs its visible run text. Do not reinterpret +/// that text as LaTeX. Keep traversal and output bounded independently of conversion. +fn math_body_text(tb: &El) -> String { + const MAX_BYTES: usize = 1 << 20; + fn append(text: &str, out: &mut String) { + let mut end = text.len().min(MAX_BYTES.saturating_sub(out.len())); + while !text.is_char_boundary(end) { + end -= 1; + } + out.push_str(&text[..end]); + } + fn visit(e: &El, depth: usize, left: &mut usize, out: &mut String) { + if depth > 64 || *left == 0 || out.len() >= MAX_BYTES { + return; + } + *left -= 1; + if e.name.ends_with("Pr") { + return; + } + if e.name == "t" { + append(&e.text, out); + } else if e.name == "AlternateContent" { + // Choice and fallback describe the same content, not two text runs. + if let Some(c) = e.child("Fallback").or_else(|| e.child("Choice")) { + visit(c, depth + 1, left, out); + } + } else { + for child in &e.children { + visit(child, depth + 1, left, out); + if *left == 0 || out.len() >= MAX_BYTES { + break; + } + } + } + } + let mut out = String::new(); + let mut left = 100_000; + for (i, p) in tb.kids("p").enumerate() { + if left == 0 || out.len() >= MAX_BYTES { + break; + } + if i > 0 { + append("\n", &mut out); + } + visit(p, 0, &mut left, &mut out); + } + out +} + /// Whether a body without Office Math still holds the text the writer wrote for `src`: the same /// paragraphs, read back through the same parser. The marker joins run text across paragraphs, /// so a paragraph split that changes no character passes it; the text does not. @@ -705,3 +754,23 @@ pub fn image_content_type(ext: &str) -> &'static str { _ => "image/png", } } + +#[cfg(test)] +mod math_fallback_tests { + use super::*; + + #[test] + fn fallback_uses_one_alternative_and_ignores_properties() { + let tb = crate::xml::parse(br#"

hiddenbefore choicefallback after

next

"#).unwrap(); + assert_eq!(math_body_text(&tb), "before fallback after\nnext"); + } + + #[test] + fn fallback_output_cap_keeps_utf8_intact() { + let xml = format!("

a{}

", "λ".repeat(1 << 19)); + let tb = crate::xml::parse(xml.as_bytes()).unwrap(); + let text = math_body_text(&tb); + assert_eq!(text.len(), (1 << 20) - 1); + assert!(text.starts_with('a') && text.ends_with('λ')); + } +} diff --git a/crates/xlsx/src/omml.rs b/crates/xlsx/src/omml.rs index cb7c7cf03..0e1c4d071 100644 --- a/crates/xlsx/src/omml.rs +++ b/crates/xlsx/src/omml.rs @@ -13,6 +13,7 @@ pub fn to_latex(e: &El) -> Option { if e.name != "oMathPara" && e.name != "oMath" { return None; } + validate_conversion(e, 0, false, &mut (1 << 20))?; let mut xml = String::new(); write_el(e, &mut xml); let math = craft_math::omml::read_str(&xml)?; @@ -21,6 +22,72 @@ pub fn to_latex(e: &El) -> Option { (!out.is_empty() && gridcraft_math::check(&out).is_ok()).then_some(out) } +// The shared reader is tolerant; this importer must fall back instead of losing +// equation content. Bound escaped XML before serializing or descending further. +fn validate_conversion(e: &El, depth: usize, property: bool, remaining: &mut usize) -> Option<()> { + if depth > MAX_DEPTH { + return None; + } + let charge = e.name.len().checked_mul(2)?.checked_add(16)?.checked_add(e.text.len().checked_mul(6)?)?; + *remaining = remaining.checked_sub(charge)?; + for (key, value) in &e.attrs { + *remaining = remaining.checked_sub(key.len().checked_add(value.len().checked_mul(6)?)?.checked_add(8)?)?; + } + let property = property || e.name.ends_with("Pr"); + if !property + && !matches!( + e.name.as_str(), + "oMath" + | "oMathPara" + | "r" + | "t" + | "f" + | "num" + | "den" + | "rad" + | "deg" + | "e" + | "sSup" + | "sSub" + | "sSubSup" + | "sPre" + | "sub" + | "sup" + | "nary" + | "d" + | "m" + | "mr" + | "eqArr" + | "acc" + | "bar" + | "groupChr" + | "limLow" + | "limUpp" + | "lim" + | "func" + | "fName" + | "borderBox" + | "phant" + | "box" + ) + { + return None; + } + // These limits truncate in the shared reader rather than refusing the matrix. + if (e.name == "m" && e.kids("mr").count() > 1000) || (e.name == "mr" && e.kids("e").count() > 64) { + return None; + } + // The pinned emitter treats a literal caret as syntax. Preserve original text + // rather than inventing a superscript; structural scripts remain supported. + if e.name == "t" && e.text.contains('^') { + return None; + } + for child in &e.children { + validate_conversion(child, depth + 1, property, remaining)?; + } + Some(()) +} + fn write_el(e: &El, out: &mut String) { out.push_str("x"), None); + assert_eq!( + latex( + "xy" + ), + None + ); + assert_eq!(latex("x^2"), None); + assert_eq!(latex("x2").as_deref(), Some("{x}^{2}")); + let cells = "x".repeat(65); + assert_eq!(latex(&format!("{cells}")), None); + } + + #[test] + fn literal_run_property_invalidates_the_saved_source_marker() { + let plain = el("x"); + let literal = el("x"); + assert_ne!(body_marker(&plain), body_marker(&literal)); + assert_eq!(body_marker(&plain), body_marker(&plain.clone())); + } + #[test] fn the_subset_reads_back() { assert_eq!(latex("x+1").as_deref(), Some("x+1")); diff --git a/crates/xlsx/src/tests/equation_tests.rs b/crates/xlsx/src/tests/equation_tests.rs index 0d6f7476c..223419768 100644 --- a/crates/xlsx/src/tests/equation_tests.rs +++ b/crates/xlsx/src/tests/equation_tests.rs @@ -483,3 +483,44 @@ fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() { // The Office Math box keeps the size of the equation. assert!(!d.contains(""), "{d}"); } + +#[test] +fn rejected_office_math_without_a_saved_source_keeps_visible_text() { + let wb = book(vec![equation(1, "B2", "x^2", Color::Auto)]); + let original = unzip(&write_xlsx(&wb).unwrap()); + let name = original.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let d = drawing(&original); + let c0 = d.find("").unwrap(); + let choice = &d[c0..c1]; + let mut sp = choice[choice.find("").unwrap() + "".len(); + for (body, expected) in [ + ("x^2", "x^2"), + ( + "Solve: x^2 pleasenext", + "Solve: x^2 please\nnext", + ), + ("λ^2", "λ^2"), + ] { + let mut shape = sp.clone(); + let start = shape.find("").unwrap(); + let end = shape.find("").unwrap() + "".len(); + shape.replace_range(start..end, &format!("{body}")); + let mut xml = d.clone(); + xml.replace_range(a0..a1, &shape); + let mut parts = original.clone(); + parts.insert(name.clone(), xml.into_bytes()); + let back = shapes(&read_xlsx(&rezip(&parts)).unwrap().0); + assert_eq!(back.len(), 1); + assert_ne!(back[0].kind, ShapeKind::Equation); + assert_eq!(back[0].text, expected); + let again = shapes(&read_xlsx(&write_xlsx(&book(back)).unwrap()).unwrap().0); + assert_eq!(again[0].text, expected); + } +}