office: char-level merge for spreadsheet cells + slide text (SheetDocCodec/SlideDocCodec), wired via charKind; tests
- Commit
7d39d9a06930d79d5705d1e0a6d10789cde808fa- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-06 19:26 UTC (5 months ago)
- Parents
4338ecb
Diff
office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeSync.ktindex 87e13644f3..bcbd678ae6 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt@@ -110,9 +110,9 @@ object OfficeSync { // --- Inbox channel (invites encrypted to the recipient's public key) --- /** Shares a document by dropping an encrypted invite into the recipient's inbox channel. */- suspend fun sendInvite(recipientId: String, docId: String, key: ByteArray, title: String, charMode: Boolean, role: String, ownerKeyB64: String): Boolean {+ suspend fun sendInvite(recipientId: String, docId: String, key: ByteArray, title: String, charMode: Boolean, role: String, ownerKeyB64: String, charKind: String): Boolean { val peerBundle = getKey(recipientId) ?: return false- val invite = json.encodeToString(Invite(docId, Base64.encode(key), title, charMode, role, ownerKeyB64))+ val invite = json.encodeToString(Invite(docId, Base64.encode(key), title, charMode, role, ownerKeyB64, charKind)) val blob = Base64.encode(Pqc.encryptTo(peerBundle, invite.encodeToByteArray())) return append("inbox:$recipientId", listOf(blob)) != null }@@ -279,6 +279,7 @@ object OfficeSync { val charMode: Boolean = false, val role: String = "editor", val ownerKey: String = "",+ val charKind: String = "", ) class InvitesResult(val invites: List<Invite>, val seq: Int)
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 29e31847dc..38ce05a7f4 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -34,6 +34,7 @@ data class OfficeDocMeta( val charMode: Boolean = false, val role: String = OfficeRoles.EDITOR, val ownerKeyB64: String = "",+ val charKind: String = "", // "", "text", "sheet", or "slide" ) /** Builds the local metadata for a shared document from an incoming invite (carries role + owner key). */@@ -46,6 +47,7 @@ fun officeDocMetaFromInvite(inv: OfficeSync.Invite): OfficeDocMeta = charMode = inv.charMode, role = inv.role, ownerKeyB64 = inv.ownerKey,+ charKind = inv.charKind, ) /** Document access roles. Enforced entirely client-side via signature checks (server is a pure relay). */@@ -305,7 +307,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) currentDocId = onlineDocId currentDocKey = onlineDocKey currentCrdt = null- currentCharMode = false+ currentCharKind = "" _isOnline.value = onlineDocId != null if (onlineDocId == null) { // Offline document: you own your own local file and may edit it freely.@@ -356,7 +358,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) currentDocId = null currentDocKey = null currentCrdt = null- currentCharMode = false+ currentCharKind = "" OfficeSync.stopLive() livePollJob?.cancel() presenceTickJob?.cancel()@@ -370,7 +372,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) // --- Create new documents --- fun createNewTextDocument() {- currentDocId = null; currentDocKey = null; currentCrdt = null; currentCharMode = false+ currentDocId = null; currentDocKey = null; currentCrdt = null; currentCharKind = "" currentRole = OfficeRoles.OWNER; currentOwnerKey = null; currentMembers.clear(); _isOnline.value = false undoStack.clear(); redoStack.clear() _canUndo.value = false; _canRedo.value = false@@ -385,7 +387,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) } fun createNewSpreadsheet() {- currentDocId = null; currentDocKey = null; currentCrdt = null; currentCharMode = false+ currentDocId = null; currentDocKey = null; currentCrdt = null; currentCharKind = "" currentRole = OfficeRoles.OWNER; currentOwnerKey = null; currentMembers.clear(); _isOnline.value = false undoStack.clear(); redoStack.clear() _canUndo.value = false; _canRedo.value = false@@ -401,7 +403,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) } fun createNewPresentation() {- currentDocId = null; currentDocKey = null; currentCrdt = null; currentCharMode = false+ currentDocId = null; currentDocKey = null; currentCrdt = null; currentCharKind = "" currentRole = OfficeRoles.OWNER; currentOwnerKey = null; currentMembers.clear(); _isOnline.value = false undoStack.clear(); redoStack.clear() _canUndo.value = false; _canRedo.value = false@@ -2017,7 +2019,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) private var currentDocId: String? = null private var currentDocKey: ByteArray? = null private var currentCrdt: DocumentCrdt? = null- private var currentCharMode: Boolean = false+ private var currentCharKind: String = "" // "", "text", "sheet", or "slide" private var currentRole: String = OfficeRoles.OWNER private var currentOwnerKey: ByteArray? = null private var currentEpoch: Int = 0@@ -2279,16 +2281,39 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) /** Projects the open document to CRDT cells: character cells for eligible text docs, else XML lines. */ private fun currentDocCells(): List<String> { val doc = (_state.value as? ViewState.Loaded)?.document- return if (currentCharMode && doc is OdfDocument.TextDocument) TextDocCodec.toCells(doc)- else OfficeCrdtCodec.toLines(exportFlat())+ return when {+ 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())+ } } /** Rebuilds a document from merged cells (char cells → model directly; else XML lines → parse). */ private fun rebuildDoc(cells: List<String>): OdfDocument? { val base = (_state.value as? ViewState.Loaded)?.document- return if (currentCharMode && base is OdfDocument.TextDocument)- runCatching { TextDocCodec.fromCells(cells, base) }.getOrNull()- else parseFlat(OfficeCrdtCodec.fromLines(cells))+ val title = base?.title ?: "Document"+ return when {+ currentCharKind == "text" -> runCatching {+ TextDocCodec.fromCells(cells, base as? OdfDocument.TextDocument ?: OdfDocument.TextDocument(title, emptyList()))+ }.getOrNull()+ currentCharKind == "sheet" -> runCatching {+ SheetDocCodec.fromCells(cells, base as? OdfDocument.Spreadsheet ?: OdfDocument.Spreadsheet(title, emptyList()))+ }.getOrNull()+ currentCharKind == "slide" -> runCatching {+ SlideDocCodec.fromCells(cells, base as? OdfDocument.Presentation ?: OdfDocument.Presentation(title, emptyList()))+ }.getOrNull()+ else -> parseFlat(OfficeCrdtCodec.fromLines(cells))+ }+ }++ /** Which char-level codec (if any) a document is eligible for: "text"/"sheet"/"slide", or "". */+ private fun charKindOf(doc: OdfDocument?): String = when {+ doc == null -> ""+ TextDocCodec.isEligible(doc) -> "text"+ SheetDocCodec.isEligible(doc) -> "sheet"+ SlideDocCodec.isEligible(doc) -> "slide"+ else -> "" } private suspend fun syncDoc(docId: String, key: ByteArray) = syncMutex.withLock {@@ -2339,7 +2364,8 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) // The owner names the document when it first goes online; later shares keep that name. val title = if (firstShare) docName.trim().ifBlank { doc?.title ?: "Document" } else (currentOnlineTitle() ?: doc?.title ?: "Document")- val charMode = doc != null && TextDocCodec.isEligible(doc)+ val charKind = charKindOf(doc)+ val charMode = charKind.isNotEmpty() val docId = currentDocId ?: OfficeSync.newDocumentId() val key = currentDocKey ?: OfficeSync.newDocumentKey() if (firstShare) {@@ -2360,14 +2386,14 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) else -> { currentDocId = docId currentDocKey = key- currentCharMode = charMode+ currentCharKind = charKind _isOnline.value = true val ownerKeyB64 = Base64.encode(OfficeSync.publicBundle) syncDoc(docId, key) indexMutex.withLock { val index = loadIndex(ds).associateBy { it.docId }.toMutableMap() if (!index.containsKey(docId)) {- index[docId] = OfficeDocMeta(docId, title, Base64.encode(key), owner = true, charMode = charMode, role = OfficeRoles.OWNER, ownerKeyB64 = ownerKeyB64)+ index[docId] = OfficeDocMeta(docId, title, Base64.encode(key), owner = true, charMode = charMode, role = OfficeRoles.OWNER, ownerKeyB64 = ownerKeyB64, charKind = charKind) saveIndex(ds, index.values.toList()) } }@@ -2376,7 +2402,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) OfficeMember(OfficeSync.deviceId, myName(), OfficeRoles.OWNER), OfficeMember(recipientId, "", role), ))- if (OfficeSync.sendInvite(recipientId, docId, key, title, charMode, role, ownerKeyB64)) null+ if (OfficeSync.sendInvite(recipientId, docId, key, title, charMode, role, ownerKeyB64, charKind)) null else "Couldn't deliver the invite — check your connection." } }@@ -2440,23 +2466,34 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) } return@runCatching }- val flat = if (meta.charMode) {- val base = OdfDocument.TextDocument(title = title, content = emptyList())- val doc = runCatching { TextDocCodec.fromCells(cells, base) }.getOrNull() ?: base- OdfSerializer.serializeFlat(doc)- } else {- OfficeCrdtCodec.fromLines(cells)+ val kind = meta.charKind.ifEmpty { if (meta.charMode) "text" else "" }+ val flat: String+ val ext: String+ when (kind) {+ "text" -> {+ val base = OdfDocument.TextDocument(title = title, content = emptyList())+ flat = OdfSerializer.serializeFlat(runCatching { TextDocCodec.fromCells(cells, base) }.getOrNull() ?: base); ext = "fodt"+ }+ "sheet" -> {+ val base = OdfDocument.Spreadsheet(title = title, sheets = emptyList())+ flat = OdfSerializer.serializeFlat(runCatching { SheetDocCodec.fromCells(cells, base) }.getOrNull() ?: base); ext = "fods"+ }+ "slide" -> {+ 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" } } val ctx: Context = getApplication() val safeTitle = title.replace(Regex("[^A-Za-z0-9._-]"), "_").ifBlank { "document" }- val file = java.io.File(ctx.cacheDir, "online_${meta.docId}.fodt")+ val file = java.io.File(ctx.cacheDir, "online_${meta.docId}.$ext") file.writeText(flat) withContext(Dispatchers.Main) {- loadDocument(Uri.fromFile(file), "$safeTitle.fodt", meta.docId, key)+ loadDocument(Uri.fromFile(file), "$safeTitle.$ext", meta.docId, key) _isEditMode.value = OfficeRoles.canEdit(meta.role) // viewers are read-only } currentCrdt = crdt- currentCharMode = meta.charMode+ currentCharKind = meta.charKind.ifEmpty { if (meta.charMode) "text" else "" } startLive(meta.docId, key) } }
office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.kt b/office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.ktnew file mode 100644index 0000000000..e6649a46be--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/util/SheetDocCodec.kt@@ -0,0 +1,123 @@+package com.vayunmathur.office.util++import androidx.compose.ui.text.style.TextAlign+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Projects an [OdfDocument.Spreadsheet] to/from a flat list of cells so [DocumentCrdt] merges cell+ * *text* at character granularity (two people editing the same cell converge without clobbering).+ *+ * Layout per sheet: the characters of each cell, a `C` terminator carrying the cell's non-text+ * attributes (formula/style), an `R` terminator per row, and an `S` terminator per sheet carrying the+ * sheet's layout. Only spreadsheets whose content the codec can fully represent are eligible (see+ * [isEligible]); anything richer (images, merged cells, borders, floating objects) uses the lossless+ * line-level codec.+ */+object SheetDocCodec {+ private const val SEP = '\u0002'+ private val json = Json { ignoreUnknownKeys = true }++ @Serializable+ data class CellMeta(+ val formula: String? = null, val valueType: String? = null,+ val bold: Boolean = false, val italic: Boolean = false,+ val textColor: Long? = null, val bg: Long? = null, val align: String? = null,+ )++ @Serializable+ data class SheetMeta(+ val name: String,+ val colWidths: List<Float?> = emptyList(),+ val rowHeights: List<Float?> = emptyList(),+ val freezeRows: Int = 0, val freezeCols: Int = 0,+ val hidden: Boolean = false, val tabColor: Long? = null,+ )++ fun isEligible(doc: OdfDocument): Boolean {+ if (doc !is OdfDocument.Spreadsheet) return false+ if (doc.images.isNotEmpty() || doc.namedRanges.isNotEmpty() || doc.validations.isNotEmpty()) return false+ for (sheet in doc.sheets) {+ if (sheet.floating.isNotEmpty()) return false+ for (row in sheet.rows) for (c in row.cells) {+ if (c.borders != null || c.isCovered || c.spannedColumns != 1 || c.rowSpan != 1) return false+ }+ }+ return true+ }++ fun toCells(doc: OdfDocument.Spreadsheet): List<String> {+ val cells = ArrayList<String>()+ for (sheet in doc.sheets) {+ for (row in sheet.rows) {+ for (cell in row.cells) {+ for (ch in cell.text) cells.add("c$SEP$ch")+ cells.add("C$SEP${json.encodeToString(cellMeta(cell))}")+ }+ cells.add("R$SEP")+ }+ cells.add("S$SEP${json.encodeToString(sheetMeta(sheet))}")+ }+ return cells+ }++ fun fromCells(cells: List<String>, base: OdfDocument.Spreadsheet): OdfDocument.Spreadsheet {+ val sheets = ArrayList<OdfSheet>()+ var rows = ArrayList<OdfRow>()+ var rowCells = ArrayList<OdfCell>()+ val text = StringBuilder()+ for (cell in cells) {+ val sep = cell.indexOf(SEP)+ if (sep < 0) continue+ val kind = cell.substring(0, sep)+ val value = cell.substring(sep + 1)+ when (kind) {+ "c" -> text.append(value)+ "C" -> {+ val m = runCatching { json.decodeFromString<CellMeta>(value) }.getOrNull() ?: CellMeta()+ rowCells.add(OdfCell(+ text = text.toString(), formula = m.formula, valueType = m.valueType,+ bold = m.bold, italic = m.italic, textColor = m.textColor, backgroundColor = m.bg,+ alignment = parseAlign(m.align),+ ))+ text.clear()+ }+ "R" -> { rows.add(OdfRow(rowCells)); rowCells = ArrayList() }+ "S" -> {+ val m = runCatching { json.decodeFromString<SheetMeta>(value) }.getOrNull() ?: SheetMeta("Sheet")+ sheets.add(OdfSheet(+ name = m.name, rows = rows, columnWidths = m.colWidths, rowHeights = m.rowHeights,+ freezeRows = m.freezeRows, freezeCols = m.freezeCols, hidden = m.hidden, tabColor = m.tabColor,+ ))+ rows = ArrayList()+ }+ }+ }+ if (sheets.isEmpty()) sheets.add(OdfSheet("Sheet 1", listOf(OdfRow(listOf(OdfCell(text = ""))))))+ return base.copy(sheets = sheets)+ }++ private fun cellMeta(c: OdfCell) = CellMeta(+ formula = c.formula, valueType = c.valueType, bold = c.bold, italic = c.italic,+ textColor = c.textColor, bg = c.backgroundColor, align = c.alignment?.let { alignName(it) },+ )++ private fun sheetMeta(s: OdfSheet) = SheetMeta(+ name = s.name, colWidths = s.columnWidths, rowHeights = s.rowHeights,+ freezeRows = s.freezeRows, freezeCols = s.freezeCols, hidden = s.hidden, tabColor = s.tabColor,+ )++ private fun alignName(a: TextAlign): String = when (a) {+ TextAlign.Start -> "start"; TextAlign.End -> "end"; TextAlign.Center -> "center"+ TextAlign.Justify -> "justify"; TextAlign.Left -> "left"; TextAlign.Right -> "right"; else -> "start"+ }++ private fun parseAlign(s: String?): TextAlign? = when (s) {+ "start" -> TextAlign.Start; "end" -> TextAlign.End; "center" -> TextAlign.Center+ "justify" -> TextAlign.Justify; "left" -> TextAlign.Left; "right" -> TextAlign.Right; else -> null+ }+}
office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.kt b/office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.ktnew file mode 100644index 0000000000..ff417b7871--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/util/SlideDocCodec.kt@@ -0,0 +1,130 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Projects an [OdfDocument.Presentation] to/from a flat cell list so [DocumentCrdt] merges slide+ * text-box text at character granularity. Eligible only for presentations whose elements are all+ * text frames (no images/charts/shapes, no slide notes/background image); richer decks use the+ * lossless line-level codec.+ *+ * Layout: per slide, per frame, per paragraph → the paragraph's characters (each carrying its span+ * style), a `P` terminator (paragraph style), an `E` terminator per frame (geometry/fill), and a `D`+ * terminator per slide (name/background/transition).+ */+object SlideDocCodec {+ private const val SEP = '\u0002'+ private const val CSEP = '\u0003'+ private val json = Json { ignoreUnknownKeys = true }++ @Serializable+ data class SpanStyle(val b: Boolean = false, val i: Boolean = false, val u: Boolean = false, val sz: Float? = null, val col: Long? = null)++ @Serializable+ data class FrameMeta(val x: Float, val y: Float, val w: Float, val h: Float, val fill: Long? = null, val stroke: Long? = null, val strokeW: Float? = null)++ @Serializable+ data class SlideMeta(val name: String, val bg: Long? = null, val transitionType: String? = null, val transitionSpeed: String? = null, val masterName: String? = null)++ fun isEligible(doc: OdfDocument): Boolean {+ if (doc !is OdfDocument.Presentation) return false+ if (doc.images.isNotEmpty()) return false+ for (slide in doc.slides) {+ if (slide.backgroundImagePath != null || slide.notes.isNotEmpty()) return false+ for (el in slide.elements) {+ val f = (el as? OdfSlideElement.Frame)?.frame ?: return false+ if (f.image != null || f.chart != null) return false+ }+ }+ return true+ }++ fun toCells(doc: OdfDocument.Presentation): List<String> {+ val cells = ArrayList<String>()+ for (slide in doc.slides) {+ for (el in slide.elements) {+ val f = (el as OdfSlideElement.Frame).frame+ for (para in f.paragraphs) {+ for (span in para.spans) {+ val key = json.encodeToString(spanStyle(span))+ for (ch in span.text) cells.add("c$SEP$key$CSEP$ch")+ }+ cells.add("P$SEP${para.style.name}")+ }+ cells.add("E$SEP${json.encodeToString(frameMeta(f))}")+ }+ cells.add("D$SEP${json.encodeToString(slideMeta(slide))}")+ }+ return cells+ }++ fun fromCells(cells: List<String>, base: OdfDocument.Presentation): OdfDocument.Presentation {+ val slides = ArrayList<OdfSlide>()+ var elements = ArrayList<OdfSlideElement>()+ var paras = ArrayList<OdfParagraph>()+ var spans = ArrayList<OdfSpan>()+ var curKey: String? = null+ val text = StringBuilder()++ fun flushSpan() {+ if (curKey != null && text.isNotEmpty()) {+ val s = runCatching { json.decodeFromString<SpanStyle>(curKey!!) }.getOrNull() ?: SpanStyle()+ spans.add(OdfSpan(text = text.toString(), bold = s.b, italic = s.i, underline = s.u, fontSize = s.sz, color = s.col))+ }+ text.clear()+ }+ fun flushPara(styleName: String) {+ flushSpan()+ val style = runCatching { ParagraphStyle.valueOf(styleName) }.getOrNull() ?: ParagraphStyle.BODY+ paras.add(OdfParagraph(spans = if (spans.isEmpty()) listOf(OdfSpan("")) else spans, style = style))+ spans = ArrayList(); curKey = null+ }++ for (cell in cells) {+ val sep = cell.indexOf(SEP)+ if (sep < 0) continue+ val kind = cell.substring(0, sep)+ val value = cell.substring(sep + 1)+ when (kind) {+ "c" -> {+ val cs = value.indexOf(CSEP)+ if (cs < 0) continue+ val key = value.substring(0, cs); val ch = value.substring(cs + 1)+ if (key != curKey) { flushSpan(); curKey = key }+ text.append(ch)+ }+ "P" -> flushPara(value)+ "E" -> {+ val m = runCatching { json.decodeFromString<FrameMeta>(value) }.getOrNull() ?: FrameMeta(0f, 0f, 100f, 40f)+ elements.add(OdfSlideElement.Frame(OdfFrame(+ x = m.x, y = m.y, width = m.w, height = m.h, paragraphs = paras,+ fillColor = m.fill, strokeColor = m.stroke, strokeWidth = m.strokeW,+ )))+ paras = ArrayList()+ }+ "D" -> {+ val m = runCatching { json.decodeFromString<SlideMeta>(value) }.getOrNull() ?: SlideMeta("Slide")+ slides.add(OdfSlide(+ name = m.name, elements = elements, backgroundColor = m.bg,+ transitionType = m.transitionType, transitionSpeed = m.transitionSpeed, masterName = m.masterName,+ ))+ elements = ArrayList()+ }+ }+ }+ if (slides.isEmpty()) slides.add(OdfSlide("Slide 1"))+ return base.copy(slides = slides)+ }++ private fun spanStyle(s: OdfSpan) = SpanStyle(b = s.bold, i = s.italic, u = s.underline, sz = s.fontSize, col = s.color)+ private fun frameMeta(f: OdfFrame) = FrameMeta(f.x, f.y, f.width, f.height, f.fillColor, f.strokeColor, f.strokeWidth)+ private fun slideMeta(s: OdfSlide) = SlideMeta(s.name, s.backgroundColor, s.transitionType, s.transitionSpeed, s.masterName)+}
office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.ktnew file mode 100644index 0000000000..ec6b74a7ec--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/SheetDocCodecTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class SheetDocCodecTest {++ private fun sheet(vararg rows: List<String>) = OdfDocument.Spreadsheet(+ title = "s",+ sheets = listOf(OdfSheet("Sheet 1", rows.map { r -> OdfRow(r.map { OdfCell(text = it) }) }))+ )++ private fun cellTexts(doc: OdfDocument.Spreadsheet) = doc.sheets[0].rows.map { row -> row.cells.map { it.text } }++ @Test+ fun roundtrip_preserves_cells_and_style() {+ val doc = OdfDocument.Spreadsheet(+ title = "s",+ sheets = listOf(OdfSheet("Data", listOf(+ OdfRow(listOf(OdfCell(text = "Name", bold = true), OdfCell(text = "Total", formula = "=SUM(A1:A2)", valueType = "float"))),+ OdfRow(listOf(OdfCell(text = "x"), OdfCell(text = "5")))+ )))+ )+ val rebuilt = SheetDocCodec.fromCells(SheetDocCodec.toCells(doc), doc)+ assertEquals(cellTexts(doc), cellTexts(rebuilt))+ assertEquals("Data", rebuilt.sheets[0].name)+ assertTrue(rebuilt.sheets[0].rows[0].cells[0].bold)+ assertEquals("=SUM(A1:A2)", rebuilt.sheets[0].rows[0].cells[1].formula)+ }++ @Test+ fun concurrent_edits_same_cell_merge_char_level() {+ val base = sheet(listOf("Hello"))+ val a = DocumentCrdt("A"); val baseOps = a.update(SheetDocCodec.toCells(base))+ val b = DocumentCrdt("B"); b.apply(baseOps)+ val opsA = a.update(SheetDocCodec.toCells(sheet(listOf("Hello World")))) // append " World"+ val opsB = b.update(SheetDocCodec.toCells(sheet(listOf("Hi Hello")))) // prepend "Hi "+ a.apply(opsB); b.apply(opsA)+ assertEquals(a.render(), b.render())+ val merged = SheetDocCodec.fromCells(a.render(), base)+ val text = merged.sheets[0].rows[0].cells[0].text+ assertTrue("has A's edit", text.contains("World"))+ assertTrue("has B's edit", text.contains("Hi"))+ assertEquals("still one row", 1, merged.sheets[0].rows.size)+ assertEquals("still one cell (no duplication)", 1, merged.sheets[0].rows[0].cells.size)+ }++ @Test+ fun concurrent_new_rows_merge() {+ val base = sheet(listOf("r1"))+ val a = DocumentCrdt("A"); val baseOps = a.update(SheetDocCodec.toCells(base))+ val b = DocumentCrdt("B"); b.apply(baseOps)+ val opsA = a.update(SheetDocCodec.toCells(sheet(listOf("r1"), listOf("from-A"))))+ val opsB = b.update(SheetDocCodec.toCells(sheet(listOf("r1"), listOf("from-B"))))+ a.apply(opsB); b.apply(opsA)+ assertEquals(a.render(), b.render())+ val merged = SheetDocCodec.fromCells(a.render(), base)+ val allText = merged.sheets[0].rows.flatMap { it.cells }.joinToString("|") { it.text }+ assertTrue(allText.contains("from-A"))+ assertTrue(allText.contains("from-B"))+ assertTrue(allText.contains("r1"))+ }++ @Test+ fun ineligible_when_merged_cells_or_images() {+ assertTrue(SheetDocCodec.isEligible(sheet(listOf("a"))))+ val merged = OdfDocument.Spreadsheet(title = "s", sheets = listOf(OdfSheet("S", listOf(OdfRow(listOf(OdfCell(text = "a", spannedColumns = 2)))))))+ assertTrue(!SheetDocCodec.isEligible(merged))+ }+}
office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.kt b/office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.ktnew file mode 100644index 0000000000..9540e73e1d--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/SlideDocCodecTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class SlideDocCodecTest {++ private fun frame(text: String) = OdfSlideElement.Frame(+ OdfFrame(x = 0f, y = 0f, width = 100f, height = 40f, paragraphs = listOf(OdfParagraph(listOf(OdfSpan(text)))))+ )++ private fun deck(vararg frameTexts: String) = OdfDocument.Presentation(+ title = "p", slides = listOf(OdfSlide("Slide 1", elements = frameTexts.map { frame(it) }))+ )++ private fun frameTexts(doc: OdfDocument.Presentation) =+ doc.slides[0].elements.map { (it as OdfSlideElement.Frame).frame.paragraphs.joinToString("") { p -> p.spans.joinToString("") { s -> s.text } } }++ @Test+ fun roundtrip_preserves_frames_and_bold() {+ val doc = OdfDocument.Presentation(title = "p", slides = listOf(OdfSlide("Intro", elements = listOf(+ OdfSlideElement.Frame(OdfFrame(10f, 20f, 300f, 80f, listOf(OdfParagraph(listOf(OdfSpan("Title", bold = true)))))),+ frame("Body text")+ ))))+ val rebuilt = SlideDocCodec.fromCells(SlideDocCodec.toCells(doc), doc)+ assertEquals(frameTexts(doc), frameTexts(rebuilt))+ assertEquals("Intro", rebuilt.slides[0].name)+ val firstFrame = (rebuilt.slides[0].elements[0] as OdfSlideElement.Frame).frame+ assertEquals(10f, firstFrame.x)+ assertTrue(firstFrame.paragraphs[0].spans[0].bold)+ }++ @Test+ fun concurrent_edits_same_textbox_merge_char_level() {+ val base = deck("Hello")+ val a = DocumentCrdt("A"); val baseOps = a.update(SlideDocCodec.toCells(base))+ val b = DocumentCrdt("B"); b.apply(baseOps)+ val opsA = a.update(SlideDocCodec.toCells(deck("Hello World")))+ val opsB = b.update(SlideDocCodec.toCells(deck("Hi Hello")))+ a.apply(opsB); b.apply(opsA)+ assertEquals(a.render(), b.render())+ val merged = SlideDocCodec.fromCells(a.render(), base)+ val text = frameTexts(merged)[0]+ assertTrue("has A's edit", text.contains("World"))+ assertTrue("has B's edit", text.contains("Hi"))+ assertEquals("still one text box (no duplication)", 1, merged.slides[0].elements.size)+ }++ @Test+ fun ineligible_when_slide_has_image_frame() {+ assertTrue(SlideDocCodec.isEligible(deck("a")))+ val withImage = OdfDocument.Presentation(title = "p", slides = listOf(OdfSlide("S", elements = listOf(+ OdfSlideElement.Frame(OdfFrame(0f, 0f, 10f, 10f, emptyList(), image = com.vayunmathur.library.ui.odf.OdfImage(path = "x", imageData = ByteArray(0))))+ ))))+ assertTrue(!SlideDocCodec.isEligible(withImage))+ }+}