Merge pull request #4166 from vangel76/fix/4162-nested-equation-colours

Nested equation colours stay per part after reopening a file
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 10:07:56 +01:00
commit 5fb3b44f69
3 files changed
+209 -2

No files matched your search

+10
View File
@@ -637,6 +637,16 @@ mod tests {
assert_eq!(c, vec![Some([255, 0, 0]), None]);
}
#[test]
fn nested_colours_are_kept_per_glyph() {
// Green a, + and c; black b and the plain +d are left to the equation's own colour.
let l = layout("{\\color{green}a+{\\color{black}b}+c}+d").unwrap();
let g = Some([0, 128, 0]);
let c: Vec<(char, Option<[u8; 3]>)> =
l.items.iter().filter_map(|i| if let Item::Glyph(g) = i { Some((g.ch, g.color)) } else { None }).collect();
assert_eq!(c, vec![('a', g), ('+', g), ('b', None), ('+', g), ('c', g), ('+', None), ('d', None)]);
}
#[test]
fn errors_point_at_the_source() {
let e = layout("a + \\frac{1}{").unwrap_err();
+66 -2
View File
@@ -283,15 +283,19 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
let descr = obj.path(&["nvSpPr", "cNvPr"]).and_then(|c| c.attr("descr")).unwrap_or("");
let tb = obj.child("txBody");
let has_math = tb.is_some_and(|tb| crate::omml::find_math(tb, 0).is_some());
// The description's source is GridCraft's own only while its marker matches; the saved frame
// ink belongs to that body alone, not to Office Math another application rewrote.
let mut own = false;
let source = match (has_math, described_source(descr)) {
(_, Some((marker, src))) if tb.is_some_and(|tb| crate::omml::body_marker(tb) == marker && (has_math || holds_written_text(tb, src))) => {
own = true;
Some(src.to_string())
}
(true, _) => tb.and_then(crate::omml::equation_source),
(false, _) => None,
};
if let Some(text) = source {
let ink = obj.child("txBody").and_then(|tb| first_run_color(tb, 0)).unwrap_or_default();
let ink = equation_ink(tb, &text, own, has_math);
return Some(Shape {
id: 0,
kind: ShapeKind::Equation,
@@ -368,6 +372,66 @@ fn described_source(descr: &str) -> Option<(&str, &str)> {
(rest.as_bytes().get(16) == Some(&b':') && marker.bytes().all(|b| b.is_ascii_hexdigit()) && !src.trim().is_empty()).then_some((marker, src))
}
/// The colour an equation's frame carries (its "ink": the colour of everything the source does
/// not colour itself). GridCraft saves it on its own Office Math paragraph's `a:endParaRPr`;
/// another writer's paragraph-end formatting is not that convention, so its first run's colour
/// stands in, as do the runs of a body without Office Math (one colour throughout: the plain-text
/// box of an equation outside the subset). The runs of GridCraft's own Office Math cannot stand
/// in when the source colours some of them (`{\color{green}a}+d` would read back green), so such
/// a source with no saved ink reads as Automatic, unless every run carries the same colour: that
/// is how earlier versions saved an explicit ink (on each run, with no paragraph-end fill).
fn equation_ink(tb: Option<&El>, source: &str, own: bool, has_math: bool) -> Color {
let Some(tb) = tb else { return Color::default() };
if own && has_math {
if let Some(c) = tb.kids("p").find_map(|p| p.child("endParaRPr")).and_then(|e| e.child("solidFill")).and_then(dml_color) {
return c;
}
if source.contains("\\color") || source.contains("\\textcolor") {
return uniform_run_color(tb).unwrap_or_default();
}
}
first_run_color(tb, 0).unwrap_or_default()
}
/// The colour every run under `e` carries, or `None` when there is no run, a run has no fill or
/// the runs differ.
fn uniform_run_color(e: &El) -> Option<Color> {
let mut found: Option<Color> = None;
let mut mixed = false;
collect_run_colors(e, 0, &mut found, &mut mixed);
if mixed { None } else { found }
}
fn collect_run_colors(e: &El, depth: usize, found: &mut Option<Color>, mixed: &mut bool) {
if depth > 12 || *mixed {
return;
}
if e.name == "rPr" {
// Office Math's own run style (`m:rPr`: bold, plain, script) sits beside the DrawingML one
// that carries the fill, and the parser drops the prefix that tells them apart
if is_math_run_style(e) {
return;
}
match (e.child("solidFill").and_then(dml_color), *found) {
(None, _) => *mixed = true,
(Some(c), None) => *found = Some(c),
(Some(c), Some(f)) if c != f => *mixed = true,
_ => {}
}
return;
}
for c in &e.children {
collect_run_colors(c, depth + 1, found, mixed);
}
}
/// Whether `e` is an Office Math `m:rPr` (only style children such as `m:sty`), not the DrawingML
/// `a:rPr` of the run, which holds the fill and the font.
fn is_math_run_style(e: &El) -> bool {
const MATH_STYLE: [&str; 6] = ["nor", "sty", "scr", "lit", "aln", "brk"];
!e.children.is_empty() && e.children.iter().all(|c| MATH_STYLE.contains(&c.name.as_str()))
}
/// The colour of the first run (DrawingML `rPr` with a fill) under `e`.
fn first_run_color(e: &El, depth: usize) -> Option<Color> {
if depth > 12 {
@@ -428,7 +492,7 @@ fn write_equation(s: &mut String, sh: &Shape, id: usize, theme: &Theme) {
match gridcraft_math::to_omml(&sh.text, size_pt, sh.line.resolve(theme)) {
Ok(omml) => {
let math = format!(
"<a:p><a:pPr algn=\"ctr\"/><a14:m><m:oMathPara xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><m:oMathParaPr><m:jc m:val=\"centerGroup\"/></m:oMathParaPr>{omml}</m:oMathPara></a14:m><a:endParaRPr lang=\"en-US\" sz=\"{sz}\"/></a:p>"
"<a:p><a:pPr algn=\"ctr\"/><a14:m><m:oMathPara xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><m:oMathParaPr><m:jc m:val=\"centerGroup\"/></m:oMathParaPr>{omml}</m:oMathPara></a14:m><a:endParaRPr lang=\"en-US\" sz=\"{sz}\">{fill}</a:endParaRPr></a:p>"
);
let _ = write!(
s,
+133
View File
@@ -469,6 +469,139 @@ fn a_paragraph_split_in_an_equation_without_office_math_reads_back_as_the_edit()
assert_eq!(s[0].text, cd.replacen(' ', " \n", 1), "the split text, exactly");
}
/// The saved Office Math of `src` with its first run coloured green (as a coloured source is
/// written when the converter carries `\color`), read back; `keep_descr` keeps GridCraft's own
/// source in the description, else the equation is another writer's Office Math.
fn first_run_green(src: &str, ink: Color, keep_descr: bool) -> Shape {
let wb = book(vec![equation(1, "B2", src, ink)]);
let mut parts = unzip(&write_xlsx(&wb).unwrap());
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
let mut d = drawing(&parts);
let at = d.find("<a:rPr lang=\"en-US\"").unwrap();
let close = d[at..].find('>').unwrap() + at + 1;
let green = "<a:solidFill><a:srgbClr val=\"008000\"/></a:solidFill>";
match d[close..].starts_with("<a:solidFill>") {
true => {
let end = d[close..].find("</a:solidFill>").unwrap() + close + "</a:solidFill>".len();
d.replace_range(close..end, green);
}
false => d.insert_str(close, green),
}
if !keep_descr {
let a = d.find(" descr=\"gridcraft:latex:").unwrap();
let b = d[a + 8..].find('"').unwrap() + a + 9;
d.replace_range(a..b, "");
}
parts.insert(name, d.into_bytes());
let s = shapes(&read_xlsx(&rezip(&parts)).unwrap().0);
assert_eq!(s.len(), 1);
assert_eq!(s[0].kind, ShapeKind::Equation);
s[0].clone()
}
#[test]
fn a_coloured_run_in_gridcraft_s_own_equation_is_not_the_frames_ink() {
// `b` and `+d` have no colour of their own: they take the frame's ink, not the green of the
// first run, which would paint the whole equation green after reopening the file.
let src = "{\\color{green}a+{\\color{black}b}+c}+d";
assert_eq!(first_run_green(src, Color::Auto, true).line, Color::Auto);
assert_eq!(first_run_green(src, Color::Rgb(0x1F4E79), true).line, Color::Rgb(0x1F4E79));
// A source without a colour command keeps reading the run colour (files saved before the
// paragraph carried the ink), and another writer's Office Math too.
assert_eq!(first_run_green("a+b", Color::Auto, true).line, Color::Rgb(0x008000));
assert_eq!(first_run_green("a+b", Color::Auto, false).line, Color::Rgb(0x008000));
}
#[test]
fn another_writer_s_paragraph_end_colour_is_not_the_frames_ink() {
// Another writer's Office Math with a green first run and a blue paragraph end: the blue
// `a:endParaRPr` is that writer's formatting, not GridCraft's saved ink, so the first run's
// colour stays the frame's ink as before.
let s = first_run_green("a+b", Color::Rgb(0x0000FF), false);
assert_eq!(s.line, Color::Rgb(0x008000));
}
#[test]
fn an_equation_whose_office_math_was_rewritten_reads_its_first_run_as_the_frames_ink() {
// GridCraft's description is still there, but another application changed the Office Math
// (`b` became `c`), so the marker no longer matches and the equation is rebuilt from the
// Office Math. The blue paragraph end GridCraft saved is not its ink any more: the green
// first run stands in, and the next save writes that back instead of the stale blue.
let wb = book(vec![equation(1, "B2", "a+b", Color::Rgb(0x0000FF))]);
let mut parts = unzip(&write_xlsx(&wb).unwrap());
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
let mut d = drawing(&parts);
assert!(d.contains("<m:t>b</m:t>"), "the second operand is its own run: {d}");
d = d.replacen("<m:t>b</m:t>", "<m:t>c</m:t>", 1);
let at = d.find("<a:rPr lang=\"en-US\"").unwrap();
let close = d[at..].find('>').unwrap() + at + 1;
let green = "<a:solidFill><a:srgbClr val=\"008000\"/></a:solidFill>";
match d[close..].starts_with("<a:solidFill>") {
true => {
let end = d[close..].find("</a:solidFill>").unwrap() + close + "</a:solidFill>".len();
d.replace_range(close..end, green);
}
false => d.insert_str(close, green),
}
parts.insert(name, d.into_bytes());
let s = shapes(&read_xlsx(&rezip(&parts)).unwrap().0);
assert_eq!((s.len(), s[0].kind, s[0].text.as_str()), (1, ShapeKind::Equation, "a+c"), "rebuilt from the Office Math");
assert_eq!(s[0].line, Color::Rgb(0x008000));
}
#[test]
fn a_coloured_equation_without_office_math_keeps_its_frame_ink() {
// `\begin{CD}` is outside the Office Math subset, so the equation is saved as the plain-text
// box alone, whose runs all carry the frame's ink; the colour command in the source does not
// make that ink Automatic on reopening.
let src = "{\\color{red}A} \\begin{CD} A @>f>> B \\end{CD}";
for ink in [Color::Rgb(0x0000FF), Color::Auto] {
let bytes = write_xlsx(&book(vec![equation(1, "B2", src, ink)])).unwrap();
assert!(!drawing(&unzip(&bytes)).contains("<a14:m>"), "written without Office Math");
let s = shapes(&read_xlsx(&bytes).unwrap().0);
assert_eq!((s.len(), s[0].kind, s[0].text.as_str(), s[0].line), (1, ShapeKind::Equation, src, ink));
}
}
#[test]
fn nested_colours_keep_the_frame_ink_through_save_and_reopen() {
// The combined round trip: the uncoloured parts (`b`, `+d`) take the frame's ink, so saving
// and reopening, twice, must leave that ink as it was rather than the source's green.
let src = "{\\color{green}a+{\\color{black}b}+c}+d";
for ink in [Color::Auto, Color::Rgb(0x1F4E79)] {
let mut wb = book(vec![equation(1, "B2", src, ink)]);
for _ in 0..2 {
let bytes = write_xlsx(&wb).unwrap();
assert!(drawing(&unzip(&bytes)).contains("<a14:m>"), "written as Office Math");
wb = read_xlsx(&bytes).unwrap().0;
let s = shapes(&wb);
assert_eq!((s.len(), s[0].kind, s[0].text.as_str(), s[0].line), (1, ShapeKind::Equation, src, ink));
}
}
}
#[test]
fn a_workbook_saved_before_the_paragraph_carried_the_ink_keeps_its_explicit_frame_ink() {
// The earlier writer put the frame's ink on every Office Math run and wrote no fill on the
// paragraph end: strip that fill from a saved equation to get the same bytes. The styled
// runs (`\\mathbf`, `\\text`) also carry an `m:rPr` of Office Math style beside the `a:rPr`.
let src = "{\\color{green}a+{\\color{black}\\mathbf{b}}+\\text{c}}+d";
let wb = book(vec![equation(1, "B2", src, Color::Rgb(0x1F4E79))]);
let mut parts = unzip(&write_xlsx(&wb).unwrap());
let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone();
let d = drawing(&parts);
assert!(d.contains("<m:rPr><m:sty"), "a styled run writes an Office Math run style: {d}");
let at = d.find("<a:endParaRPr").unwrap();
let open_end = d[at..].find('>').unwrap() + at + 1;
let close = d[open_end..].find("</a:endParaRPr>").unwrap() + open_end;
assert!(d[open_end..close].contains("1F4E79"), "the paragraph end carries the ink: {d}");
let legacy = format!("{}{}", &d[..open_end], &d[close..]);
assert!(legacy.matches("1F4E79").count() > 1, "every run still carries the ink");
parts.insert(name, legacy.into_bytes());
let s = shapes(&read_xlsx(&rezip(&parts)).unwrap().0);
assert_eq!((s.len(), s[0].kind, s[0].text.as_str(), s[0].line), (1, ShapeKind::Equation, src, Color::Rgb(0x1F4E79)));
}
#[test]
fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() {
// A source Office Math cannot hold is saved as the text box alone; a source it can hold has