Modern Apps git

← Modern-Apps.git

office: nested ODF spans no longer lose the outer formatting

Commit
d69b222800bf7ce06c68b22785237255f1cd052e
Author
Vayun Mathur <[email protected]>
When
2026-12-01 03:24 UTC (5 days ago)
Parents
208eb54
The ODF inline parser held a single current style: a nested
<text:span> overwrote it, and the inner </text:span> reset
it to null instead of restoring the enclosing span. For
'bold <span>both</span> tail', 'both' loaded italic-only
(the outer bold lost) and ' tail' loaded unstyled instead of
resuming bold โ€” and re-saving permanently stripped the
formatting the document arrived with.

InlineAcc now keeps style/href stacks (span/a start pushes,
end pops and restores), and makeEffectiveSpan layers the
enclosing styles: flags OR together, innermost wins for
valued properties like size/color, super/subscript innermost
wins. Footnote/annotation paths flush through the same
effective-style path. Three regression tests failed pre-fix
on exactly these losses. Verified: :office:testDevUnitTest
549 tests pass; lint errors are pre-existing on untouched
files.

Diff

office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt
diff --git a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.ktindex a428c277e8..8ba193bb51 100644--- a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt+++ b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInline.kt@@ -21,8 +21,45 @@ internal fun OdfParser.makeSpan(     styleName: String?,     styles: Map<String,     StyleInfo>,-    href: String? = null): OdfSpan {-    val resolved = resolveStyle(styleName, styles)+    href: String? = null): OdfSpan = spanFromStyle(text, resolveStyle(styleName, styles), href)++/** Layers [inner] over [outer]: inner wins for valued properties, flags accumulate. */+private fun layerStyle(outer: StyleInfo, inner: StyleInfo): StyleInfo = outer.copy(+    bold = outer.bold || inner.bold,+    italic = outer.italic || inner.italic,+    fontSize = inner.fontSize ?: outer.fontSize,+    fontFamily = inner.fontFamily ?: outer.fontFamily,+    underline = outer.underline || inner.underline,+    strikethrough = outer.strikethrough || inner.strikethrough,+    color = inner.color ?: outer.color,+    backgroundColor = inner.backgroundColor ?: outer.backgroundColor,+    superscript = if (inner.superscript || inner.subscript) inner.superscript else outer.superscript,+    subscript = if (inner.superscript || inner.subscript) inner.subscript else outer.subscript,+    underlineStyle = inner.underlineStyle ?: outer.underlineStyle,+    underlineColor = inner.underlineColor ?: outer.underlineColor,+    letterSpacing = inner.letterSpacing ?: outer.letterSpacing,+    textTransform = inner.textTransform ?: outer.textTransform,+    language = inner.language ?: outer.language,+    country = inner.country ?: outer.country+)++/**+ * Span for text under the whole nested-span stack in [acc]: enclosing <text:span>+ * layers contribute their formatting, the innermost layer winning valued properties.+ */+internal fun OdfParser.makeEffectiveSpan(+    text: String,+    acc: InlineAcc,+    styles: Map<String, StyleInfo>): OdfSpan {+    var effective = StyleInfo()+    for (name in acc.styleStack + acc.currentStyleName) {+        effective = layerStyle(effective, resolveStyle(name, styles))+    }+    return spanFromStyle(text, effective, acc.currentHref)+}++/** Builds a span from an already-resolved style. */+private fun OdfParser.spanFromStyle(text: String, resolved: StyleInfo, href: String?): OdfSpan {     return OdfSpan(         text = text,         bold = resolved.bold,@@ -50,6 +87,9 @@ internal class InlineAcc(     val textBuffer: StringBuilder = StringBuilder(),     var currentStyleName: String? = null,     var currentHref: String? = null,+    // Enclosing <text:span>/<text:a> contexts, restored when the inner element ends.+    val styleStack: ArrayDeque<String?> = ArrayDeque(),+    val hrefStack: ArrayDeque<String?> = ArrayDeque(),     var pendingFrameW: Float = 0f,     var pendingFrameH: Float = 0f,     var pendingFrameClip: String? = null,@@ -96,13 +136,13 @@ internal fun OdfParser.parseInlineContent(     return spans } -private fun OdfParser.flushInlineBuf(+internal fun OdfParser.flushInlineBuf(     acc: InlineAcc,     spans: MutableList<OdfSpan>,     styles: Map<String, StyleInfo>, ) {     if (acc.textBuffer.isNotEmpty()) {-        spans.add(makeSpan(acc.textBuffer.toString(), acc.currentStyleName, styles, acc.currentHref))+        spans.add(makeEffectiveSpan(acc.textBuffer.toString(), acc, styles))         acc.textBuffer.clear()     } }@@ -127,10 +167,12 @@ private fun OdfParser.applyInlineStyleTag(     when (parser.name) {         "span" -> {             flushInlineBuf(acc, spans, ctx.styles)+            acc.styleStack.addLast(acc.currentStyleName)             acc.currentStyleName = getAttr(parser, "style-name")         }         "a" -> {             flushInlineBuf(acc, spans, ctx.styles)+            acc.hrefStack.addLast(acc.currentHref)             acc.currentHref = getAttr(parser, "href")         }         "tab" -> acc.textBuffer.append("\t")@@ -193,7 +235,7 @@ private fun OdfParser.applyInlineField(     flushInlineBuf(acc, spans, styles)     val kind = parser.name     val fb = readInlineFieldBody(parser)-    spans.add(makeSpan(fb, acc.currentStyleName, styles, acc.currentHref).copy(field = kind))+    spans.add(makeEffectiveSpan(fb, acc, styles).copy(field = kind)) }  private fun OdfParser.readInlineFieldBody(parser: XmlPullParser): String {@@ -217,11 +259,11 @@ private fun OdfParser.applyInlineEndTag(     when (parser.name) {         "span" -> {             flushInlineBuf(acc, spans, ctx.styles)-            acc.currentStyleName = null+            acc.currentStyleName = if (acc.styleStack.isNotEmpty()) acc.styleStack.removeLast() else null         }         "a" -> {             flushInlineBuf(acc, spans, ctx.styles)-            acc.currentHref = null+            acc.currentHref = if (acc.hrefStack.isNotEmpty()) acc.hrefStack.removeLast() else null         }     } }@@ -274,10 +316,7 @@ private fun OdfParser.applyReferenceRef(     styles: Map<String, StyleInfo>,     spans: MutableList<OdfSpan>, ) {-    if (acc.textBuffer.isNotEmpty()) {-        spans.add(makeSpan(acc.textBuffer.toString(), acc.currentStyleName, styles, acc.currentHref))-        acc.textBuffer.clear()-    }+    flushInlineBuf(acc, spans, styles)     val kind = parser.name     val refName = getAttr(parser, "ref-name")     val refFormat = getAttr(parser, "reference-format")@@ -287,7 +326,7 @@ private fun OdfParser.applyReferenceRef(         if (ev == XmlPullParser.END_DOCUMENT) break         ev = parser.next()     }-    spans.add(makeSpan(fb.toString(), acc.currentStyleName, styles, acc.currentHref)+    spans.add(makeEffectiveSpan(fb.toString(), acc, styles)         .copy(refKind = kind, refName = refName, refFormat = refFormat, color = LINK_COLOR)) } @@ -304,10 +343,7 @@ private fun OdfParser.applyTitleDesc(     // consume the whole subtree so its text never leaks into the paragraph. (alt-text fix)     val isSvg = parser.namespace?.contains("svg") == true     val isField = !isSvg && parser.name in FIELD_TAGS-    if (acc.textBuffer.isNotEmpty() && (isSvg || isField)) {-        spans.add(makeSpan(acc.textBuffer.toString(), acc.currentStyleName, styles, acc.currentHref))-        acc.textBuffer.clear()-    }+    if (isSvg || isField) flushInlineBuf(acc, spans, styles)     val kind = parser.name     val raw = readInlineFieldBody(parser)     applyTitleDescResult(kind, raw, raw.trim(), isSvg, isField, acc, styles, spans, imagesOut)@@ -326,14 +362,7 @@ private fun OdfParser.applyTitleDescResult( ) {     when {         isSvg -> attachSvgAltText(kind, trimmed, imagesOut)-        isField -> spans.add(-            makeSpan(-                raw,-                acc.currentStyleName,-                styles,-                acc.currentHref-            ).copy(field = kind)-        )+        isField -> spans.add(makeEffectiveSpan(raw, acc, styles).copy(field = kind))     } } 
office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInlineMedia.kt
diff --git a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInlineMedia.kt b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInlineMedia.ktindex fb9ef13741..c02060cdae 100644--- a/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInlineMedia.kt+++ b/office/src/main/java/com/vayunmathur/office/data/odf/OdfParserInlineMedia.kt@@ -113,10 +113,7 @@ internal fun OdfParser.applyInlineNote(     spans: MutableList<OdfSpan>,     footnotes: MutableList<com.vayunmathur.library.ui.odf.OdfFootnote>?, ) {-    if (acc.textBuffer.isNotEmpty()) {-        spans.add(makeSpan(acc.textBuffer.toString(), acc.currentStyleName, styles, acc.currentHref))-        acc.textBuffer.clear()-    }+    flushInlineBuf(acc, spans, styles)     val fn = parseFootnote(parser, styles)     if (fn != null) {         footnotes?.add(fn)@@ -131,10 +128,7 @@ internal fun OdfParser.applyInlineAnnotation(     styles: Map<String, StyleInfo>,     spans: MutableList<OdfSpan>, ) {-    if (acc.textBuffer.isNotEmpty()) {-        spans.add(makeSpan(acc.textBuffer.toString(), acc.currentStyleName, styles, acc.currentHref))-        acc.textBuffer.clear()-    }+    flushInlineBuf(acc, spans, styles)     val annotation = parseAnnotation(parser, styles)     if (annotation != null) {         spans.add(OdfSpan(text = " ๐Ÿ“ ", annotation = annotation))
office/src/test/java/com/vayunmathur/office/data/odf/OdfNestedSpanTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/data/odf/OdfNestedSpanTest.kt b/office/src/test/java/com/vayunmathur/office/data/odf/OdfNestedSpanTest.ktnew file mode 100644index 0000000000..263466bb1a--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/data/odf/OdfNestedSpanTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.office.data.odf++import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Regression: nested <text:span> elements. ODF producers (LibreOffice etc.) nest spans+ * to layer formatting, e.g. italic inside bold. The tail after the inner span must resume+ * the outer span's formatting, and the inner text must combine both layers.+ */+class OdfNestedSpanTest {++    private val head =+        """<?xml version="1.0" encoding="UTF-8"?>""" ++            """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++            """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++            """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++            """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++            """xmlns:xlink="http://www.w3.org/1999/xlink">"""++    private val textStyles =+        """<style:style style:name="B" style:family="text">""" ++            """<style:text-properties fo:font-weight="bold"/></style:style>""" ++            """<style:style style:name="I" style:family="text">""" ++            """<style:text-properties fo:font-style="italic"/></style:style>"""++    private fun doc(body: String): OdfDocument.TextDocument =+        OdfParser.parseTextXml(+            head ++                "<office:automatic-styles>$textStyles</office:automatic-styles>" ++                "<office:body><office:text>$body</office:text></office:body></office:document>"+        )++    private fun spansOf(d: OdfDocument.TextDocument) =+        d.content.filterIsInstance<OdfContentBlock.Paragraph>().single().paragraph.spans++    @Test+    fun nested_span_tail_resumes_outer_formatting() {+        val d = doc(+            """<text:p><text:span text:style-name="B">bold """ ++                """<text:span text:style-name="I">both</text:span> tail</text:span> plain</text:p>"""+        )+        val spans = spansOf(d)+        assertEquals(listOf("bold ", "both", " tail", " plain"), spans.map { it.text })+        assertTrue(spans[0].bold); assertFalse(spans[0].italic)+        assertTrue(spans[1].bold); assertTrue(spans[1].italic)+        assertTrue(spans[2].bold); assertFalse(spans[2].italic)+        assertFalse(spans[3].bold); assertFalse(spans[3].italic)+    }++    @Test+    fun triple_nested_span_unwinds_one_level_at_a_time() {+        val d = doc(+            """<text:p><text:span text:style-name="B">a""" ++                """<text:span text:style-name="I">b</text:span>c</text:span></text:p>"""+        )+        val spans = spansOf(d)+        assertEquals(listOf("a", "b", "c"), spans.map { it.text })+        assertTrue(spans[2].bold); assertFalse(spans[2].italic)+    }++    @Test+    fun link_inside_span_keeps_outer_formatting_and_tail_loses_href() {+        val d = doc(+            """<text:p><text:span text:style-name="B">bold """ ++                """<text:a xlink:href="https://example.com">link</text:a> tail</text:span></text:p>"""+        )+        val spans = spansOf(d)+        assertEquals(listOf("bold ", "link", " tail"), spans.map { it.text })+        assertEquals("https://example.com", spans[1].href)+        assertTrue(spans[1].bold)+        assertEquals(null, spans[2].href)+        assertTrue(spans[2].bold)+    }+}