Modern Apps git

← Modern-Apps.git

office: universal character-level merge for ALL documents via FlatXmlCharCodec (char-merge text in any flat ODF; binary/tags opaque); tests

Commit
c217d1507e91509112d9790531eb201920911f68
Author
Vayun Mathur <[email protected]>
When
2026-07-06 19:40 UTC (5 months ago)
Parents
7f41771

Diff

office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.kt b/office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.ktnew file mode 100644index 0000000000..c994c18931--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/util/FlatXmlCharCodec.kt@@ -0,0 +1,61 @@+package com.vayunmathur.office.util++/**+ * Universal character-level projection of a **flat ODF XML** document: text content between tags+ * becomes individual character cells (char-merged by [DocumentCrdt]), while tags stay whole cells and+ * `office:binary-data` content (base64 images) stays a single opaque cell (never char-split).+ *+ * This lets *any* document — including ones with images, tables, shapes, notes — merge concurrent+ * edits to the same text region at character granularity, while non-text structure merges at element+ * granularity. Rebuild simply concatenates the cells back into the original XML, so a clean (no+ * concurrent structural conflict) merge always reproduces valid XML.+ */+object FlatXmlCharCodec {+    private const val SEP = '\u0002'++    fun toCells(xml: String): List<String> {+        val cells = ArrayList<String>(xml.length)+        val n = xml.length+        var i = 0+        var inBinary = false+        while (i < n) {+            if (xml[i] == '<') {+                // Scan to the closing '>', skipping any '>' inside quoted attribute values.+                var j = i + 1+                var quote = '\u0000'+                while (j < n) {+                    val c = xml[j]+                    when {+                        quote != '\u0000' -> if (c == quote) quote = '\u0000'+                        c == '"' || c == '\'' -> quote = c+                        c == '>' -> break+                    }+                    j+++                }+                val tag = xml.substring(i, minOf(j + 1, n))+                cells.add("t$SEP$tag")+                when {+                    tag.startsWith("<office:binary-data") -> inBinary = !tag.endsWith("/>")+                    tag.startsWith("</office:binary-data") -> inBinary = false+                }+                i = j + 1+            } else {+                val end = xml.indexOf('<', i).let { if (it < 0) n else it }+                val text = xml.substring(i, end)+                if (inBinary) cells.add("b$SEP$text") // base64 blob stays a single opaque cell+                else for (c in text) cells.add("c$SEP$c")+                i = end+            }+        }+        return cells+    }++    fun fromCells(cells: List<String>): String {+        val sb = StringBuilder()+        for (cell in cells) {+            val sep = cell.indexOf(SEP)+            if (sep >= 0) sb.append(cell.substring(sep + 1))+        }+        return sb.toString()+    }+}
office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.ktindex 38ce05a7f4..f5b6389c4e 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -2285,7 +2285,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)             currentCharKind == "text" && doc is OdfDocument.TextDocument -> TextDocCodec.toCells(doc)             currentCharKind == "sheet" && doc is OdfDocument.Spreadsheet -> SheetDocCodec.toCells(doc)             currentCharKind == "slide" && doc is OdfDocument.Presentation -> SlideDocCodec.toCells(doc)-            else -> OfficeCrdtCodec.toLines(exportFlat())+            else -> FlatXmlCharCodec.toCells(exportFlat()) // universal char-level (text within any flat ODF)         }     } @@ -2303,7 +2303,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)             currentCharKind == "slide" -> runCatching {                 SlideDocCodec.fromCells(cells, base as? OdfDocument.Presentation ?: OdfDocument.Presentation(title, emptyList()))             }.getOrNull()-            else -> parseFlat(OfficeCrdtCodec.fromLines(cells))+            else -> parseFlat(FlatXmlCharCodec.fromCells(cells))         }     } @@ -2482,7 +2482,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)                         val base = OdfDocument.Presentation(title = title, slides = emptyList())                         flat = OdfSerializer.serializeFlat(runCatching { SlideDocCodec.fromCells(cells, base) }.getOrNull() ?: base); ext = "fodp"                     }-                    else -> { flat = OfficeCrdtCodec.fromLines(cells); ext = "fodt" }+                    else -> { flat = FlatXmlCharCodec.fromCells(cells); ext = "fodt" }                 }                 val ctx: Context = getApplication()                 val safeTitle = title.replace(Regex("[^A-Za-z0-9._-]"), "_").ifBlank { "document" }
office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.ktnew file mode 100644index 0000000000..972ec843b8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/FlatXmlCharCodecTest.kt@@ -0,0 +1,66 @@+package com.vayunmathur.office.util++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class FlatXmlCharCodecTest {++    @Test+    fun roundtrip_is_exact() {+        val xml = """<office:document office:mimetype="x"><office:body><text:p>Hello &amp; world</text:p><draw:frame svg:width="1>2"/></office:body></office:document>"""+        assertEquals(xml, FlatXmlCharCodec.fromCells(FlatXmlCharCodec.toCells(xml)))+    }++    @Test+    fun tag_with_gt_in_attribute_stays_one_cell() {+        val xml = """<a b="x>y">t</a>"""+        val cells = FlatXmlCharCodec.toCells(xml)+        // The opening tag (with the '>' inside the quoted attribute) must be a single tag cell.+        assertTrue(cells.any { it == "t\u0002<a b=\"x>y\">" })+        assertEquals(xml, FlatXmlCharCodec.fromCells(cells))+    }++    @Test+    fun binary_data_is_one_opaque_cell_not_char_split() {+        val b64 = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=" // stand-in for a large image blob+        val xml = "<draw:image><office:binary-data>$b64</office:binary-data></draw:image>"+        val cells = FlatXmlCharCodec.toCells(xml)+        assertTrue("base64 kept whole", cells.any { it == "b\u0002$b64" })+        assertTrue("not char-split", cells.none { it == "c\u0002Q" && b64.startsWith("Q") && cells.count { c -> c.startsWith("c\u0002") } > 5 })+        assertEquals(xml, FlatXmlCharCodec.fromCells(cells))+    }++    @Test+    fun concurrent_edits_same_text_run_merge_char_level() {+        val base = "<office:text><text:p>Hello</text:p></office:text>"+        val a = DocumentCrdt("A"); val baseOps = a.update(FlatXmlCharCodec.toCells(base))+        val b = DocumentCrdt("B"); b.apply(baseOps)+        val opsA = a.update(FlatXmlCharCodec.toCells("<office:text><text:p>Hello World</text:p></office:text>"))+        val opsB = b.update(FlatXmlCharCodec.toCells("<office:text><text:p>Hi Hello</text:p></office:text>"))+        a.apply(opsB); b.apply(opsA)+        assertEquals(a.render(), b.render())+        val merged = FlatXmlCharCodec.fromCells(a.render())+        assertTrue("has A's edit", merged.contains("World"))+        assertTrue("has B's edit", merged.contains("Hi"))+        // Tags stay intact and balanced (one paragraph, valid structure).+        assertEquals(1, Regex("<text:p>").findAll(merged).count())+        assertEquals(1, Regex("</text:p>").findAll(merged).count())+    }++    @Test+    fun concurrent_structural_inserts_stay_wellformed() {+        val base = "<office:text><text:p>one</text:p></office:text>"+        val a = DocumentCrdt("A"); val baseOps = a.update(FlatXmlCharCodec.toCells(base))+        val b = DocumentCrdt("B"); b.apply(baseOps)+        val opsA = a.update(FlatXmlCharCodec.toCells("<office:text><text:p>one</text:p><text:p>A-para</text:p></office:text>"))+        val opsB = b.update(FlatXmlCharCodec.toCells("<office:text><text:p>one</text:p><text:p>B-para</text:p></office:text>"))+        a.apply(opsB); b.apply(opsA)+        assertEquals(a.render(), b.render())+        val merged = FlatXmlCharCodec.fromCells(a.render())+        assertTrue(merged.contains("A-para")); assertTrue(merged.contains("B-para")); assertTrue(merged.contains("one"))+        // Every <text:p> is matched by a </text:p> (no interleaved/stranded tags).+        assertEquals(Regex("<text:p>").findAll(merged).count(), Regex("</text:p>").findAll(merged).count())+        assertEquals(3, Regex("<text:p>").findAll(merged).count())+    }+}