mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-21 20:40:12 +00:00
Merge pull request #4523 from storytold/fix/omml-import-parity
Preserve OMML import fallback after shared math cutover
This commit is contained in:
@@ -272,7 +272,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
|
||||
}
|
||||
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::<String>()).collect::<Vec<_>>().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#"<txBody><p><rPr><t>hidden</t></rPr><r><t>before </t></r><AlternateContent><Choice><r><t>choice</t></r></Choice><Fallback><r><t>fallback</t></r></Fallback></AlternateContent><r><t> after</t></r></p><p><r><t>next</t></r></p></txBody>"#).unwrap();
|
||||
assert_eq!(math_body_text(&tb), "before fallback after\nnext");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_output_cap_keeps_utf8_intact() {
|
||||
let xml = format!("<txBody><p><r><t>a{}</t></r></p></txBody>", "λ".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('λ'));
|
||||
}
|
||||
}
|
||||
|
||||
+91
-1
@@ -13,6 +13,7 @@ pub fn to_latex(e: &El) -> Option<String> {
|
||||
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<String> {
|
||||
(!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("<m:");
|
||||
out.push_str(&e.name);
|
||||
@@ -205,7 +272,7 @@ fn mark_bytes(h: &mut u64, bytes: &[u8]) {
|
||||
|
||||
/// Children in order, skipping property elements.
|
||||
const PROPERTIES: &[(&str, &[&str])] = &[
|
||||
("rPr", &["nor", "sty", "scr"]),
|
||||
("rPr", &["nor", "sty", "scr", "lit"]),
|
||||
("fPr", &["type"]),
|
||||
("radPr", &["degHide"]),
|
||||
("naryPr", &["chr", "limLoc", "subHide", "supHide"]),
|
||||
@@ -232,6 +299,29 @@ mod tests {
|
||||
to_latex(&el(xml))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_does_not_accept_a_partial_equation() {
|
||||
assert_eq!(latex("<m:r><m:t>x</m:t></m:r><m:unknown/>"), None);
|
||||
assert_eq!(
|
||||
latex(
|
||||
"<m:r><m:t>x</m:t></m:r><mc:AlternateContent xmlns:mc=\"mc\"><mc:Fallback><m:r><m:t>y</m:t></m:r></mc:Fallback></mc:AlternateContent>"
|
||||
),
|
||||
None
|
||||
);
|
||||
assert_eq!(latex("<m:r><m:t>x^2</m:t></m:r>"), None);
|
||||
assert_eq!(latex("<m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e><m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup>").as_deref(), Some("{x}^{2}"));
|
||||
let cells = "<m:e><m:r><m:t>x</m:t></m:r></m:e>".repeat(65);
|
||||
assert_eq!(latex(&format!("<m:m><m:mr>{cells}</m:mr></m:m>")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_run_property_invalidates_the_saved_source_marker() {
|
||||
let plain = el("<m:r><m:t>x</m:t></m:r>");
|
||||
let literal = el("<m:r><m:rPr><m:lit/></m:rPr><m:t>x</m:t></m:r>");
|
||||
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("<m:r><m:t>x+1</m:t></m:r>").as_deref(), Some("x+1"));
|
||||
|
||||
@@ -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("<a:endParaRPr lang=\"en-US\" sz=\"1100\"/>"), "{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("<mc:Choice").unwrap();
|
||||
let c1 = d.find("</mc:Choice>").unwrap();
|
||||
let choice = &d[c0..c1];
|
||||
let mut sp = choice[choice.find("<xdr:sp ").unwrap()..].to_string();
|
||||
while let Some(a) = sp.find(" descr=\"gridcraft:latex:") {
|
||||
let b = sp[a + 8..].find('"').unwrap() + a + 9;
|
||||
sp.replace_range(a..b, "");
|
||||
}
|
||||
let a0 = d.find("<mc:AlternateContent").unwrap();
|
||||
let a1 = d.find("</mc:AlternateContent>").unwrap() + "</mc:AlternateContent>".len();
|
||||
for (body, expected) in [
|
||||
("<a:p><a14:m><m:oMath><m:r><m:t>x^2</m:t></m:r></m:oMath></a14:m></a:p>", "x^2"),
|
||||
(
|
||||
"<a:p><a:r><a:t>Solve: </a:t></a:r><a14:m><m:oMath><m:r><m:t>x^2</m:t></m:r></m:oMath></a14:m><a:r><a:t> please</a:t></a:r></a:p><a:p><a:r><a:t>next</a:t></a:r></a:p>",
|
||||
"Solve: x^2 please\nnext",
|
||||
),
|
||||
("<a:p><a14:m><m:oMath><m:unknown><m:r><m:t>λ^2</m:t></m:r></m:unknown></m:oMath></a14:m></a:p>", "λ^2"),
|
||||
] {
|
||||
let mut shape = sp.clone();
|
||||
let start = shape.find("<xdr:txBody>").unwrap();
|
||||
let end = shape.find("</xdr:txBody>").unwrap() + "</xdr:txBody>".len();
|
||||
shape.replace_range(start..end, &format!("<xdr:txBody>{body}</xdr:txBody>"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user