Modern Apps git

← Modern-Apps.git

office: add tests for sync relay, screens and parsers (82 tests)

Commit
0a0b307e5bbce51468f0a9dcf122f3733fb19725
Author
Vayun Mathur <[email protected]>
When
2026-11-16 02:06 UTC (20 days ago)
Parents
7d7235e
Coverage work (cov/w4) for the office module, whose CI baseline was
147,618 covered / 20,676 missed instructions. The remaining misses
concentrated in the sync ViewModel layer and in document rendering, so
the new tests go there first, following the module's existing harness
patterns (Robolectric + createComposeRule, the OfficeViewModel slice
harness, and scripted-transport sync tests).

What is covered:
- Sync relay positive paths (W4SyncRelayTest, W4ShareOpenOnlineTest,
  W4SyncDocMergeTest): a scripted OfficeSync.HttpTransport serves
  per-channel pulls/appends so owner-signature verification for
  members, titles, key epochs and ownership transfers runs for real,
  including forged/malformed record rejection, key-epoch resolution,
  share/open-online flows, join approval, member revocation with key
  rotation, security codes, and CRDT delta merging in syncDoc.
- ViewModel save (W4SaveTest) to ODF and OOXML targets through a test
  content provider; slide element text rebuilds for every shape kind.
- Screens (W4MainActivityTest, W4DocumentScreenRichTest,
  W4FindBarsInteractTest, W4BottomBarTest, W4FloatingHandlesTest,
  W4TextTableViewTest, W4SheetEditMathTest,
  W4ImageAnnotationViewsTest): navigation graph and join links, rich
  text/sheet/presentation rendering, find/replace and font-scale bars,
  bottom-bar formatting and insert actions, floating-element handles,
  merged table cells with real edits, the spreadsheet edit bar, image
  effects/rotation/crop, and rich MathML rendering.
- Parsers/writers (W4OdfPackageFormatsTest, W4FormulaNumFmtTest,
  W4FinalParserTest): ODF packages with every image media type, ODS
  settings freeze panes, XLSX display formats, conditional formatting
  and merges, Excel number-format and formula translation branches,
  sheet drawings, and OOXML import fallbacks.

Verified: :office:createMergedCoverageReport moves the module from
147,618 to 153,701 covered instructions (+6,083; missed 20,676 ->
14,593). :office:testDevUnitTest, :office:detekt and :office:lint
are green (final run without ignore-failures).

Diff

office/src/test/java/com/vayunmathur/office/W4DocumentScreenRichTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/W4DocumentScreenRichTest.kt b/office/src/test/java/com/vayunmathur/office/W4DocumentScreenRichTest.ktnew file mode 100644index 0000000000..67656759e2--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/W4DocumentScreenRichTest.kt@@ -0,0 +1,192 @@+package com.vayunmathur.office++import androidx.activity.ComponentActivity+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTable+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.OdfTableColumn+import com.vayunmathur.library.ui.odf.OdfTableRow+import com.vayunmathur.library.ui.odf.ParagraphStyle+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/**+ * W4: [DocumentScreen] with rich documents — tables inside text docs,+ * spreadsheet grids and presentation decks render their content, and the+ * File/View menus open their real items.+ */+@RunWith(AndroidJUnit4::class)+class W4DocumentScreenRichTest {++    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun showDoc(document: OdfDocument) {+        rule.setContent {+            OfficeLightTheme {+                DocumentScreen(+                    document = document,+                    viewModel = vm(document),+                    activity = rule.activity,+                    onBack = {},+                )+            }+        }+        rule.waitForIdle()+    }++    private fun richTextDoc() = OdfDocument.TextDocument(+        "Rich.odt",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("Rich Title")), style = ParagraphStyle.HEADING1)),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("intro body")))),+            OdfContentBlock.Table(OdfTable(+                columns = listOf(OdfTableColumn(80f), OdfTableColumn(80f)),+                rows = listOf(+                    OdfTableRow(listOf(+                        OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell alpha"))))),+                        OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell beta"))))),+                    )),+                    OdfTableRow(listOf(+                        OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell gamma"))))),+                        OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell delta"))))),+                    )),+                ),+            )),+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("bullet one")), style = ParagraphStyle.LIST_ITEM)),+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("bullet two")), style = ParagraphStyle.LIST_ITEM)),+        ),+    )++    @Test fun richTextScreenRendersTableAndLists() {+        showDoc(richTextDoc())+        rule.onNodeWithText("Rich.odt").assertIsDisplayed()+        for (cell in listOf("cell alpha", "cell beta", "cell gamma", "cell delta")) {+            rule.onNodeWithText(cell, substring = true).assertExists()+        }+        rule.onNodeWithText("bullet one", substring = true).assertExists()+        rule.onNodeWithText("bullet two", substring = true).assertExists()+    }++    @Test fun fileMenuOpensRealItems() {+        showDoc(richTextDoc())+        rule.onNodeWithText("File").performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Export", substring = true).assertExists()+        rule.onNodeWithText("Settings").assertExists()+        // Export opens the format submenu.+        rule.onNodeWithText("Export", substring = true).performClick()+        rule.waitForIdle()+    }++    @Test fun viewMenuOpensRealItems() {+        showDoc(richTextDoc())+        rule.onNodeWithText("View").performClick()+        rule.waitForIdle()+        rule.onAllNodesWithText("Outline", substring = true)[0].assertExists()+    }++    @Test fun screenRecomposesAcrossDocumentAndStateChanges() {+        var currentDoc = androidx.compose.runtime.mutableStateOf<OdfDocument>(richTextDoc())+        lateinit var viewModel: OfficeViewModel+        rule.setContent {+            val doc = currentDoc.value+            viewModel = vm(doc)+            OfficeLightTheme {+                DocumentScreen(+                    document = doc,+                    viewModel = viewModel,+                    activity = rule.activity,+                    onBack = {},+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Rich.odt").assertIsDisplayed()+        // Swap the whole document: every chrome/body restart scope re-runs+        // with changed parameters.+        rule.runOnIdle {+            currentDoc.value = OdfDocument.TextDocument(+                "Other.odt",+                listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("replacement body"))))))+        }+        rule.waitForIdle()+        rule.onNodeWithText("Other.odt").assertIsDisplayed()+        rule.runOnIdle {+            currentDoc.value = richTextDoc()+        }+        rule.waitForIdle()+        rule.onNodeWithText("Rich.odt").assertIsDisplayed()+    }++    @Test fun sheetScreenRendersGrid() {+        val sheet = OdfSheet(+            name = "Data",+            rows = listOf(+                OdfRow(listOf(OdfCell("Name"), OdfCell("Value"))),+                OdfRow(listOf(OdfCell("apples"), OdfCell("42", numberValue = 42.0))),+                OdfRow(listOf(OdfCell("pears"), OdfCell("7", numberValue = 7.0))),+            ),+            freezeRows = 1,+        )+        showDoc(OdfDocument.Spreadsheet("Book.ods", listOf(sheet)))+        rule.onNodeWithText("Book.ods").assertIsDisplayed()+        rule.onNodeWithText("apples", substring = true).assertExists()+        rule.onNodeWithText("pears", substring = true).assertExists()+    }++    @Test fun presentationScreenRendersSlides() {+        val doc = OdfDocument.Presentation(+            "Deck.odp",+            listOf(+                OdfSlide(+                    "S1",+                    listOf(+                        com.vayunmathur.library.ui.odf.OdfSlideElement.Frame(+                            com.vayunmathur.library.ui.odf.OdfFrame(+                                0f, 0f, 200f, 60f,+                                listOf(OdfParagraph(listOf(OdfSpan("deck headline")))))),+                    ),+                ),+                OdfSlide(+                    "S2",+                    listOf(+                        com.vayunmathur.library.ui.odf.OdfSlideElement.Frame(+                            com.vayunmathur.library.ui.odf.OdfFrame(+                                0f, 0f, 200f, 60f,+                                listOf(OdfParagraph(listOf(OdfSpan("second slide")))))),+                    ),+                ),+            ),+        )+        showDoc(doc)+        rule.onNodeWithText("Deck.odp").assertIsDisplayed()+        // Slide canvas + thumbnail strip both render the headline.+        kotlin.test.assertTrue(+            rule.onAllNodesWithText("deck headline", substring = true)+                .fetchSemanticsNodes().isNotEmpty())+    }+}
office/src/test/java/com/vayunmathur/office/W4FindBarsInteractTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/W4FindBarsInteractTest.kt b/office/src/test/java/com/vayunmathur/office/W4FindBarsInteractTest.ktnew file mode 100644index 0000000000..3826f20943--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/W4FindBarsInteractTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.office++import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.office.util.OfficeViewModel+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/**+ * W4: [DocumentFindBars] interactions — match navigation jumps, replace+ * one/all against the real ViewModel, match-option toggles, and the+ * font-scale bar's slider + reset.+ */+@RunWith(AndroidJUnit4::class)+class W4FindBarsInteractTest {++    @get:Rule val rule = createComposeRule()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun doc() = OdfDocument.TextDocument(+        "Doc",+        listOf(+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hello world")))),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("say hello again")))),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("other")))),+        ),+    )++    private fun show(s: DocumentScreenState, document: OdfDocument = doc()) {+        val viewModel = vm(document)+        rule.setContent {+            DocumentFindBars(+                s = s,+                document = document,+                viewModel = viewModel,+                isTextDoc = true,+                isPresentation = false,+                wordCount = 3,+                charCount = 20,+                readingTime = 1,+                scope = rememberCoroutineScope(),+                listState = rememberLazyListState(),+            )+        }+    }++    private fun textOf(viewModelDoc: OdfDocument.TextDocument): List<String> =+        viewModelDoc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .map { it.paragraph.spans.joinToString("") { span -> span.text } }++    @Test fun nextAndPrevCycleThroughMatches() {+        val s = DocumentScreenState().apply {+            showSearch = true+            searchQuery = "hello"+        }+        show(s)+        rule.onNodeWithText("1/2").assertIsDisplayed()+        rule.onAllNodesWithText("Next", substring = true)[0].performClick()+        rule.waitForIdle()+        assertEquals(1, s.findIndex)+        rule.onNodeWithText("2/2").assertIsDisplayed()+        // Prev wraps back to the first match.+        rule.onAllNodesWithText("Prev", substring = true)[0].performClick()+        rule.waitForIdle()+        assertEquals(0, s.findIndex)+    }++    @Test fun replaceOneAndAllChangeTheDocument() {+        val document = doc()+        val viewModel = vm(document)+        val s = DocumentScreenState().apply {+            showSearch = true+            searchQuery = "hello"+            replaceText = "hi"+            showReplaceBar = true+        }+        rule.setContent {+            DocumentFindBars(+                s = s, document = document, viewModel = viewModel,+                isTextDoc = true, isPresentation = false,+                wordCount = 3, charCount = 20, readingTime = 1,+                scope = rememberCoroutineScope(), listState = rememberLazyListState(),+            )+        }+        // Replace-all button ("All") rewrites both occurrences and clears the query.+        rule.onAllNodesWithText("All")[0].performClick()+        rule.waitForIdle()+        val updated = (viewModel.state.value as OfficeViewModel.ViewState.Loaded).document+        @Suppress("UNCHECKED_CAST")+        val texts = textOf(updated as OdfDocument.TextDocument)+        assertEquals(listOf("hi world", "say hi again", "other"), texts)+        assertEquals("", s.searchQuery)+    }++    @Test fun matchOptionTogglesFlipState() {+        val s = DocumentScreenState().apply {+            showSearch = true+            searchQuery = "Hello"+            showReplaceBar = true+            replaceText = "x"+        }+        show(s)+        assertTrue(!s.matchCase)+        rule.onNodeWithText("☐ Case").performClick()+        rule.waitForIdle()+        assertTrue(s.matchCase)+        rule.onNodeWithText("☐ Word").performClick()+        rule.waitForIdle()+        assertTrue(s.wholeWord)+    }++    @Test fun fontScaleBarResetRestoresDefault() {+        val s = DocumentScreenState().apply {+            showFontControl = true+            fontSizeMultiplier = 1.6f+        }+        show(s)+        rule.onAllNodesWithText("Reset")[0].performClick()+        rule.waitForIdle()+        assertEquals(1f, s.fontSizeMultiplier)+    }+}
office/src/test/java/com/vayunmathur/office/W4MainActivityTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/W4MainActivityTest.kt b/office/src/test/java/com/vayunmathur/office/W4MainActivityTest.ktnew file mode 100644index 0000000000..2c1853f631--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/W4MainActivityTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.office++import android.content.Intent+import android.net.Uri+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.rules.ActivityScenarioRule+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/**+ * W4: [MainActivity] end-to-end — the navigation graph's home route, the+ * new-document routes into the editor, and `office://join` deep links+ * arriving both cold (launch intent) and warm (onNewIntent).+ */+@RunWith(AndroidJUnit4::class)+class W4MainActivityTest {++    @get:Rule+    val rule: AndroidComposeTestRule<ActivityScenarioRule<MainActivity>, MainActivity> =+        createAndroidComposeRule<MainActivity>()++    @Test fun homeShowsTabsAndNewDocumentActions() {+        rule.onNodeWithText("Office").assertIsDisplayed()+        rule.onNodeWithText("Offline").assertExists()+        rule.onNodeWithText("Online").assertExists()+        rule.onNodeWithText("Open Document").assertExists()+        rule.onNodeWithText("New Doc").assertExists()+        rule.onNodeWithText("New Sheet").assertExists()+        rule.onNodeWithText("New Slides").assertExists()+    }++    @Test fun newDocOpensEditorRoute() {+        rule.onNodeWithText("New Doc").performClick()+        rule.waitForIdle()+        // The editor chrome (menu bar) replaces the home screen.+        rule.onNodeWithText("File").assertExists()+    }++    @Test fun joinLinkIntentIsHandledWithoutCrashing() {+        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("office://join/doc-42?owner=device-7"))+            .setClass(rule.activity, MainActivity::class.java)+        androidx.test.core.app.ActivityScenario.launch<MainActivity>(intent).use { scenario ->+            scenario.onActivity { activity ->+                kotlin.test.assertFalse(activity.isFinishing)+            }+        }+    }++    @Test fun malformedJoinLinksAreIgnored() {+        for (uri in listOf(+            "office://join/?owner=device-7",+            "office://join/doc-42",+            "office://other/doc-42?owner=device-7",+            "https://example.org/doc-42?owner=device-7",+        )) {+            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))+                .setClass(rule.activity, MainActivity::class.java)+            androidx.test.core.app.ActivityScenario.launch<MainActivity>(intent).use { scenario ->+                scenario.onActivity { activity ->+                    kotlin.test.assertFalse(activity.isFinishing)+                }+            }+        }+    }+}
office/src/test/java/com/vayunmathur/office/odf/W4FinalParserTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/W4FinalParserTest.kt b/office/src/test/java/com/vayunmathur/office/odf/W4FinalParserTest.ktnew file mode 100644index 0000000000..b3d3d23d69--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/W4FinalParserTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlideElement+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * W4 (parsers, final batch): drawings floating in spreadsheets, date+ * number formats with quoted literals, sheet-qualified formula endpoints,+ * and OOXML conditional-formatting / merge post-processing.+ */+class W4FinalParserTest {++    private val head =+        """<?xml version="1.0" encoding="UTF-8"?>""" ++            """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++            """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table: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:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++            """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" """ ++            """xmlns:xlink="http://www.w3.org/1999/xlink" """ ++            """xmlns:dc="http://purl.org/dc/elements/1.1/">"""++    private fun sheet(body: String): OdfDocument.Spreadsheet = OdfParser.parseSpreadsheet(+        head + "<office:body><office:spreadsheet>$body</office:spreadsheet></office:body></office:document>",+        emptyMap(), emptyMap(), "test",+        com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap(), emptyMap(),+    )++    // ---- sheet drawings ----++    @Test+    fun `drawings inside a sheet become floating elements`() {+        val doc = sheet(+            """<table:table table:name="S"><table:table-row>""" ++                """<table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell>""" ++                """</table:table-row>""" ++                """<draw:rect svg:x="1cm" svg:y="1cm" svg:width="2cm" svg:height="1cm"><text:p>recty</text:p></draw:rect>""" ++                """<draw:ellipse svg:x="3cm" svg:y="1cm" svg:width="2cm" svg:height="1cm"/>""" ++                """<draw:line svg:x="0cm" svg:y="0cm" svg:width="4cm" svg:height="2cm"/>""" ++                """<draw:polyline svg:x="0cm" svg:y="3cm" svg:width="4cm" svg:height="1cm"/>""" ++                """<draw:polygon svg:x="5cm" svg:y="3cm" svg:width="2cm" svg:height="2cm"/>""" ++                """<draw:frame svg:x="6cm" svg:y="0cm" svg:width="3cm" svg:height="2cm">""" ++                """<draw:text-box><text:p>framed</text:p></draw:text-box></draw:frame>""" ++                """</table:table>""")+        val floating = doc.sheets.single().floating+        assertEquals(6, floating.size, floating.toString())+        assertIs<OdfShape.Rect>((floating[0] as OdfSlideElement.Shape).shape)+        assertIs<OdfShape.Ellipse>((floating[1] as OdfSlideElement.Shape).shape)+        assertIs<OdfShape.Line>((floating[2] as OdfSlideElement.Shape).shape)+        val frame = floating[5] as OdfSlideElement.Frame+        assertEquals(+            "framed",+            frame.frame.paragraphs.joinToString("") { it.spans.joinToString("") { s -> s.text } })+    }++    // ---- ExcelNumFmt quoted-literal dates ----++    @Test+    fun `date formats keep quoted literals as tokens`() {+        val fmt = ExcelNumFmt.parse("""yyyy" year "mm" month"""")+        assertNotNull(fmt)+        assertTrue(fmt.isDate)+        assertTrue(fmt.dateTimeTokens.any { it.text?.contains("year") == true }, fmt.dateTimeTokens.toString())+        assertTrue(fmt.dateTimeTokens.any { it.kind == "year" }, fmt.dateTimeTokens.toString())+        val euroDate = ExcelNumFmt.parse("dd.mm.yyyy")+        assertNotNull(euroDate)+        assertTrue(euroDate.isDate)+    }++    // ---- ExcelFormula sheet endpoints ----++    @Test+    fun `sheet qualified ranges round trip through odf`() {+        val odf = ExcelFormula.toOdf("SUM(Sheet1!A1:Sheet1!B2)")+        val back = ExcelFormula.fromOdf(odf)+        assertTrue(back.contains("Sheet1"), back)+        assertTrue(back.contains("A1"), back)+        assertTrue(back.contains("B2"), back)+        // Whole-row with sheet endpoints collapses to row-only form.+        val rowBack = ExcelFormula.fromOdf("of:=SUM([Sheet1.A2:Sheet1.XFD2])")+        assertTrue(rowBack.contains("2:2") || rowBack.contains("Sheet1"), rowBack)+    }++    // ---- XLSX conditional formatting + merges ----++    private fun xlsx(entries: Map<String, String>): OdfDocument.Spreadsheet {+        val bos = java.io.ByteArrayOutputStream()+        java.util.zip.ZipOutputStream(bos).use { zos ->+            for ((n, c) in entries) {+                zos.putNextEntry(java.util.zip.ZipEntry(n))+                zos.write(c.toByteArray(Charsets.UTF_8))+                zos.closeEntry()+            }+        }+        return OoxmlImporter.import(bos.toByteArray(), "cf.xlsx") as OdfDocument.Spreadsheet+    }++    @Test+    fun `xlsx conditional formats and merges are resolved`() {+        val doc = xlsx(mapOf(+            "xl/workbook.xml" to ("<workbook xmlns=\"s\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++                "<sheets><sheet name=\"Data\" sheetId=\"1\" r:id=\"rId1\"/></sheets></workbook>"),+            "xl/_rels/workbook.xml.rels" to ("<Relationships xmlns=\"p\">" ++                "<Relationship Id=\"rId1\" Type=\"http://t/worksheet\" Target=\"worksheets/sheet1.xml\"/></Relationships>"),+            "xl/styles.xml" to ("<styleSheet xmlns=\"s\">" ++                "<dxfs count=\"1\"><dxf><fill><patternFill><fgColor rgb=\"FFFF0000\"/></patternFill></fill></dxf></dxfs>" ++                "<cellXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellXfs></styleSheet>"),+            "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData>" ++                "<row r=\"1\"><c r=\"A1\"><v>5</v></c><c r=\"B1\"><v>50</v></c></row>" ++                "<row r=\"2\"><c r=\"A2\"><v>1</v></c></row>" ++                "</sheetData>" ++                "<mergeCells count=\"1\"><mergeCell ref=\"A1:B1\"/></mergeCells>" ++                "<conditionalFormatting sqref=\"B1\"><cfRule type=\"cellIs\" operator=\"greaterThan\" priority=\"1\" dxfId=\"0\"><formula>10</formula></cfRule></conditionalFormatting>" ++                "<conditionalFormatting sqref=\"A2\"><cfRule type=\"cellIs\" operator=\"between\" priority=\"2\" dxfId=\"0\"><formula>0</formula><formula>10</formula></cfRule></conditionalFormatting>" ++                "</worksheet>"),+        ))+        val sheet0 = doc.sheets.single()+        val flat = sheet0.rows.flatMap { it.cells }+        // The merged anchor spans two columns and its partner is covered.+        assertTrue(flat.any { it.spannedColumns == 2 }, flat.toString())+        assertTrue(flat.any { it.isCovered }, flat.toString())+        // At least the matching conditional rule colours its cell.+        assertTrue(+            flat.any { it.condFormats.isNotEmpty() || it.backgroundColor != null },+            flat.toString())+    }+}
office/src/test/java/com/vayunmathur/office/odf/W4FormulaNumFmtTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/W4FormulaNumFmtTest.kt b/office/src/test/java/com/vayunmathur/office/odf/W4FormulaNumFmtTest.ktnew file mode 100644index 0000000000..f0752e06e5--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/W4FormulaNumFmtTest.kt@@ -0,0 +1,168 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfDocument+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * W4: [ExcelNumFmt] and [ExcelFormula] translation branches, plus+ * [OoxmlImporter] empty-document fallbacks when the primary import of a+ * package yields nothing readable.+ */+class W4FormulaNumFmtTest {++    // ---- ExcelNumFmt ----++    @Test+    fun `numfmt general and text codes yield no format`() {+        assertNull(ExcelNumFmt.parse(""))+        assertNull(ExcelNumFmt.parse("General"))+        assertNull(ExcelNumFmt.parse("general"))+        assertNull(ExcelNumFmt.parse("@"))+        assertNull(ExcelNumFmt.forBuiltin(0))+    }++    @Test+    fun `numfmt quoted literals are not date tokens`() {+        // " days" contains d/y letters but is a quoted suffix on a number.+        val fmt = ExcelNumFmt.parse("""0" days"""")+        assertNotNull(fmt)+        assertTrue(!fmt.isDate, fmt.toString())+        assertEquals(0, fmt.decimals)+        val suffixed = ExcelNumFmt.parse("""#,##0.00" units"""")+        assertNotNull(suffixed)+        assertTrue(suffixed.grouping)+        assertEquals(2, suffixed.decimals)+    }++    @Test+    fun `numfmt currency colors and conditions are stripped`() {+        val euro = ExcelNumFmt.parse("[$€-x-euro] #,##0.00;[Red](#,##0.00)")+        assertNotNull(euro)+        assertEquals("€", euro.currencySymbol)+        assertTrue(euro.grouping)+        assertEquals(2, euro.decimals)+        val conditioned = ExcelNumFmt.parse("[>100]0.0;[<=100]0")+        assertNotNull(conditioned)+        assertEquals(1, conditioned.decimals)+    }++    @Test+    fun `numfmt scientific fraction and percent kinds`() {+        val sci = ExcelNumFmt.parse("0.00E+00")+        assertNotNull(sci)+        assertTrue(sci.isScientific)+        assertEquals(2, sci.decimals)+        val frac = ExcelNumFmt.parse("# ??/??")+        assertNotNull(frac)+        assertTrue(frac.isFraction)+        assertEquals(2, frac.fractionDenominatorDigits)+        val pct = ExcelNumFmt.parse("0.00%")+        assertNotNull(pct)+        assertTrue(pct.percent)+        assertEquals(2, pct.decimals)+    }++    @Test+    fun `numfmt date and elapsed time codes`() {+        val date = ExcelNumFmt.parse("yyyy-mm-dd")+        assertNotNull(date)+        assertTrue(date.isDate)+        val time = ExcelNumFmt.parse("[h]:mm:ss")+        assertNotNull(time)+        assertTrue(time.isTime || time.isDate, time.toString())+        // Builtin ids: 14 is a date, 48 scientific, 3 grouped integer.+        assertTrue(ExcelNumFmt.forBuiltin(14)?.isDate == true)+        assertTrue(ExcelNumFmt.forBuiltin(48)?.isScientific == true)+        assertTrue(ExcelNumFmt.forBuiltin(3)?.grouping == true)+        assertNull(ExcelNumFmt.forBuiltin(999))+    }++    // ---- ExcelFormula ----++    @Test+    fun `formula refs translate both ways with sheets and absolutes`() {+        assertEquals("of:=SUM([.A1:.B2])", ExcelFormula.toOdf("SUM(A1:B2)"))+        assertEquals("=SUM(A1:B2)", ExcelFormula.fromOdf("of:=SUM([.A1:.B2])"))+        // Absolute refs keep their $ anchors in ODF form too.+        assertEquals("of:=SUM([.\$A\$1])", ExcelFormula.toOdf("SUM(\$A\$1)"))+        // Sheet-qualified refs.+        val sheetOdf = ExcelFormula.toOdf("'My Sheet'!A1")+        assertTrue(sheetOdf.contains("My Sheet"), sheetOdf)+        assertTrue(sheetOdf.contains("A1"), sheetOdf)+        val sheetBack = ExcelFormula.fromOdf(sheetOdf)+        assertTrue(sheetBack.contains("A1") && sheetBack.contains("My Sheet"), sheetBack)+        assertEquals("of:=[.A1]", ExcelFormula.toOdf("A1"))+        assertEquals("=A1", ExcelFormula.fromOdf("of:=[.A1]"))+    }++    @Test+    fun `formula whole column and row refs expand`() {+        val col = ExcelFormula.toOdf("SUM(A:A)")+        assertTrue(col.contains("1048576"), col)+        val row = ExcelFormula.toOdf("SUM(1:1)")+        assertTrue(row.contains("XFD") || row.contains("16384"), row)+        // Round-trip whole-column back to Excel form.+        assertEquals("=SUM(A:A)", ExcelFormula.fromOdf(col))+    }++    @Test+    fun `formula strings and function names are left alone`() {+        val withString = ExcelFormula.toOdf("""CONCAT("A1", B2)""")+        assertTrue(withString.contains("\"A1\""), withString)+        assertTrue(withString.contains("B2"), withString)+        // An escaped quote inside the literal does not end the string early.+        val escaped = ExcelFormula.toOdf("""CONCAT("a""A1", C3)""")+        assertTrue(escaped.contains("C3"), escaped)+        assertTrue(escaped.contains("A1"), escaped)+    }++    @Test+    fun `formula shift moves relative refs only`() {+        assertEquals("SUM(B3:B4)", ExcelFormula.shift("SUM(B2:B3)", 1, 0))+        assertEquals("C3", ExcelFormula.shift("B2", 1, 1))+        assertEquals("\$B\$2", ExcelFormula.shift("\$B\$2", 3, 3))+        assertEquals("\$B5", ExcelFormula.shift("\$B2", 3, 0))+        assertEquals("SUM(B2:B3)", ExcelFormula.shift("SUM(B2:B3)", 0, 0))+        // String literals are not shifted.+        assertEquals("""CONCAT("B2", C2)""", ExcelFormula.shift("""CONCAT("B2", B2)""", 0, 1))+    }++    // ---- OoxmlImporter fallback ----++    private fun zipOf(vararg entries: Pair<String, String>): ByteArray {+        val bos = java.io.ByteArrayOutputStream()+        java.util.zip.ZipOutputStream(bos).use { zos ->+            for ((n, c) in entries) {+                zos.putNextEntry(java.util.zip.ZipEntry(n))+                zos.write(c.toByteArray(Charsets.UTF_8))+                zos.closeEntry()+            }+        }+        return bos.toByteArray()+    }++    @Test+    fun `malformed ooxml packages fall back to empty documents`() {+        val docx = OoxmlImporter.import(+            zipOf("word/document.xml" to "<<not xml"), "broken.docx")+        assertTrue(docx is OdfDocument.TextDocument, docx.toString())+        assertEquals("broken.docx", docx?.title)++        val xlsx = OoxmlImporter.import(+            zipOf("xl/workbook.xml" to "<<not xml"), "broken.xlsx")+        assertTrue(xlsx is OdfDocument.Spreadsheet, xlsx.toString())++        val pptx = OoxmlImporter.import(+            zipOf("ppt/slides/slide1.xml" to "<<not xml"), "broken.pptx")+        assertTrue(pptx is OdfDocument.Presentation, pptx.toString())++        // A zip with no office parts at all is not an OOXML document.+        assertNull(OoxmlImporter.import(zipOf("readme.txt" to "hi"), "notes.zip"))+        // Even non-zip bytes fall back by extension so the caller can open an empty doc.+        assertTrue(OoxmlImporter.import(byteArrayOf(1, 2, 3), "raw.docx") is OdfDocument.TextDocument)+    }+}
office/src/test/java/com/vayunmathur/office/odf/W4OdfPackageFormatsTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/W4OdfPackageFormatsTest.kt b/office/src/test/java/com/vayunmathur/office/odf/W4OdfPackageFormatsTest.ktnew file mode 100644index 0000000000..9e5d43d6f0--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/W4OdfPackageFormatsTest.kt@@ -0,0 +1,293 @@+package com.vayunmathur.office.odf++import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.odf.ChartType+import com.vayunmathur.library.ui.odf.OdfChart+import com.vayunmathur.library.ui.odf.OdfChartSeries+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSpan+import java.io.ByteArrayInputStream+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * W4: ODF package writing (per-extension image media types, embedded chart+ * objects, per-type package mimetypes), ODS settings.xml freeze panes, and+ * XLSX display formatting for custom/currency/datetime number formats.+ */+@RunWith(RobolectricTestRunner::class)+class W4OdfPackageFormatsTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    init {+        Robolectric.setupContentProvider(+            Slice4ImportExportTest.Slice4Provider::class.java,+            "com.vayunmathur.office.w4test")+    }++    private var outTarget: File?+        get() = Slice4ImportExportTest.Slice4Provider.outTarget+        set(v) { Slice4ImportExportTest.Slice4Provider.outTarget = v }++    private fun contentUri(name: String): Uri = Uri.parse("content://com.vayunmathur.office.w4test/$name")++    private fun uriFor(name: String, bytes: ByteArray): Uri {+        val uri = Uri.parse("content://com.vayunmathur.office.w4src/$name")+        shadowOf(context.contentResolver).registerInputStream(uri, ByteArrayInputStream(bytes))+        return uri+    }++    private fun zipBytes(entries: Map<String, ByteArray>): ByteArray {+        val bos = java.io.ByteArrayOutputStream()+        java.util.zip.ZipOutputStream(bos).use { zos ->+            for ((n, c) in entries) {+                zos.putNextEntry(java.util.zip.ZipEntry(n))+                zos.write(c)+                zos.closeEntry()+            }+        }+        return bos.toByteArray()+    }++    private fun saveTo(name: String, doc: OdfDocument): File {+        val out = File(context.cacheDir, name)+        out.delete()+        outTarget = out+        try {+            OdfWriter.save(context, null, doc, contentUri(name))+        } finally {+            outTarget = null+        }+        assertTrue(out.exists() && out.length() > 50, "no package written for $name")+        return out+    }++    private fun entriesOf(file: File): Map<String, String> {+        val map = mutableMapOf<String, String>()+        java.util.zip.ZipFile(file).use { z ->+            val e = z.entries()+            while (e.hasMoreElements()) {+                val entry = e.nextElement()+                map[entry.name] = z.getInputStream(entry).bufferedReader().readText()+            }+        }+        return map+    }++    private fun para(text: String) = OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text))))++    // ---- OdfWriter: images, objects, mimetypes ----++    @Test+    fun `writer declares every image media type and skips placeholders`() {+        val images = mapOf(+            "Pictures/a.png" to byteArrayOf(1),+            "Pictures/b.jpg" to byteArrayOf(2),+            "Pictures/c.jpeg" to byteArrayOf(3),+            "Pictures/d.gif" to byteArrayOf(4),+            "Pictures/e.bmp" to byteArrayOf(5),+            "Pictures/f.svg" to byteArrayOf(6),+            "Pictures/g.webp" to byteArrayOf(7),+            "Pictures/h.rdf" to byteArrayOf(8),+            "Pictures/i.bin" to byteArrayOf(9),+            "inline" to byteArrayOf(10),+            "" to byteArrayOf(11),+            "Pictures/empty.png" to byteArrayOf(),+        )+        val doc = OdfDocument.TextDocument(+            "Imgs", listOf(para("with images")),+            images = images,+        )+        val file = saveTo("w4-images.odt", doc)+        try {+            val entries = entriesOf(file)+            for (name in listOf("a.png", "b.jpg", "c.jpeg", "d.gif", "e.bmp", "f.svg", "g.webp", "h.rdf", "i.bin")) {+                assertTrue(entries.containsKey("Pictures/$name"), "missing $name in ${entries.keys}")+            }+            assertTrue(!entries.containsKey("inline"), "inline placeholder must be skipped")+            assertTrue(!entries.containsKey("Pictures/empty.png"), "empty image must be skipped")+            val manifest = entries.getValue("META-INF/manifest.xml")+            assertTrue(manifest.contains("image/png"), manifest)+            assertTrue(manifest.contains("image/jpeg"), manifest)+            assertTrue(manifest.contains("image/gif"), manifest)+            assertTrue(manifest.contains("image/bmp"), manifest)+            assertTrue(manifest.contains("image/svg+xml"), manifest)+            assertTrue(manifest.contains("image/webp"), manifest)+            assertTrue(manifest.contains("application/rdf+xml"), manifest)+            assertTrue(manifest.contains("application/vnd.oasis.opendocument.text"), manifest)+        } finally {+            file.delete()+        }+    }++    @Test+    fun `writer embeds chart objects and per-type mimetypes`() {+        val chart = OdfChart(+            type = ChartType.BAR,+            categories = listOf("Q1", "Q2"),+            series = listOf(OdfChartSeries("Sales", listOf(3f, 4f))),+            title = "Sales",+        )+        val docs: List<Pair<String, OdfDocument>> = listOf(+            "w4-chart.odt" to OdfDocument.TextDocument("C", listOf(OdfContentBlock.Chart(chart))),+            "w4-sheet.ods" to OdfDocument.Spreadsheet("S", listOf(OdfSheet("Data", emptyList()))),+            "w4-slides.odp" to OdfDocument.Presentation("P", listOf(OdfSlide("S1"))),+            "w4-draw.odg" to OdfDocument.Drawing("D", listOf(OdfSlide("P1"))),+        )+        val expectedMime = mapOf(+            "w4-chart.odt" to "application/vnd.oasis.opendocument.text",+            "w4-sheet.ods" to "application/vnd.oasis.opendocument.spreadsheet",+            "w4-slides.odp" to "application/vnd.oasis.opendocument.presentation",+            "w4-draw.odg" to "application/vnd.oasis.opendocument.graphics",+        )+        for ((name, doc) in docs) {+            val file = saveTo(name, doc)+            try {+                val entries = entriesOf(file)+                assertEquals(expectedMime[name], entries["mimetype"]?.trim())+                assertTrue(entries.containsKey("content.xml"), entries.keys.toString())+                if (name == "w4-chart.odt") {+                    assertTrue(+                        entries.keys.any { it.contains("content.xml") && entries[it]!!.contains("Sales") } ||+                            entries.keys.any { it.endsWith(".xml") },+                        entries.keys.toString())+                }+            } finally {+                file.delete()+            }+        }+    }++    // ---- OdfParser: settings.xml freeze panes ----++    @Test+    fun `ods settings freeze panes apply per sheet`() {+        val content = """<?xml version="1.0" encoding="UTF-8"?>""" ++            """<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++            """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++            """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">""" ++            """<office:body><office:spreadsheet>""" ++            """<table:table table:name="Data"><table:table-row><table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell></table:table-row></table:table>""" ++            """<table:table table:name="Free"><table:table-row><table:table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:table-cell></table:table-row></table:table>""" ++            """<table:table table:name="Fallback"><table:table-row><table:table-cell office:value-type="float" office:value="3"><text:p>3</text:p></table:table-cell></table:table-row></table:table>""" ++            """</office:spreadsheet></office:body></office:document-content>"""+        fun entry(name: String, items: Map<String, String>): String =+            """<config:config-item-map-entry config:name="$name">""" ++                items.entries.joinToString("") { (k, v) ->+                    """<config:config-item config:name="$k" config:type="int">$v</config:config-item>"""+                } + "</config:config-item-map-entry>"+        val settings = """<?xml version="1.0" encoding="UTF-8"?>""" ++            """<office:document-settings xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++            """xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0">""" ++            """<office:settings>""" ++            """<config:config-item config:name="VisibleAreaWidth" config:type="int">999</config:config-item>""" ++            """<config:config-item-map-indexed config:name="Views">""" ++            """<config:config-item-map-entry>""" ++            """<config:config-item-map-named config:name="Tables">""" ++            entry("Data", mapOf(+                "HorizontalSplitMode" to "2", "HorizontalSplitPosition" to "2",+                "VerticalSplitMode" to "2", "VerticalSplitPosition" to "1",+                "PositionRight" to "9", "PositionBottom" to "8")) ++            entry("Free", mapOf(+                "HorizontalSplitMode" to "0", "HorizontalSplitPosition" to "4",+                "VerticalSplitMode" to "1", "VerticalSplitPosition" to "3")) ++            entry("Fallback", mapOf(+                "HorizontalSplitMode" to "2", "VerticalSplitMode" to "2",+                "PositionRight" to "3", "PositionBottom" to "2")) ++            """</config:config-item-map-named>""" ++            """<config:config-item-map-named config:name="Other">""" ++            entry("Data", mapOf("HorizontalSplitMode" to "2", "HorizontalSplitPosition" to "7")) ++            """</config:config-item-map-named>""" ++            """</config:config-item-map-entry></config:config-item-map-indexed>""" ++            """</office:settings></office:document-settings>"""+        val bytes = zipBytes(mapOf(+            "content.xml" to content.encodeToByteArray(),+            "settings.xml" to settings.encodeToByteArray(),+            "mimetype" to "application/vnd.oasis.opendocument.spreadsheet".encodeToByteArray(),+        ))+        val doc = OdfParser.parse(context, uriFor("frozen.ods", bytes), "frozen.ods")+        val sheet = assertIs<OdfDocument.Spreadsheet>(doc)+        val byName = sheet.sheets.associateBy { it.name }+        assertEquals(1, byName["Data"]?.freezeRows)+        assertEquals(2, byName["Data"]?.freezeCols)+        assertEquals(0, byName["Free"]?.freezeRows)+        assertEquals(0, byName["Free"]?.freezeCols)+        // Fallback positions are used when the explicit split positions are absent/zero.+        assertEquals(2, byName["Fallback"]?.freezeRows)+        assertEquals(3, byName["Fallback"]?.freezeCols)+    }++    // ---- OoxmlXlsx: custom number/date formats (Kotlin fallback formatter) ----++    private fun xlsxWithFormats(formats: List<Pair<Int, String>>, cells: String): OdfDocument.Spreadsheet {+        val numFmts = formats.joinToString("") { (id, code) ->+            """<numFmt numFmtId="$id" formatCode="$code"/>"""+        }+        val xfs = (listOf("""<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>""") ++            formats.map { (id, _) ->+                """<xf numFmtId="$id" fontId="0" fillId="0" borderId="0" applyNumberFormat="1"/>"""+            }).joinToString("")+        val entries = mapOf(+            "xl/workbook.xml" to ("<workbook xmlns=\"s\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++                "<sheets><sheet name=\"Data\" sheetId=\"1\" r:id=\"rId1\"/></sheets></workbook>"),+            "xl/_rels/workbook.xml.rels" to ("<Relationships xmlns=\"p\">" ++                "<Relationship Id=\"rId1\" Type=\"http://t/worksheet\" Target=\"worksheets/sheet1.xml\"/></Relationships>"),+            "xl/styles.xml" to ("<styleSheet xmlns=\"s\"><numFmts count=\"${formats.size}\">$numFmts</numFmts>" ++                "<cellXfs count=\"${formats.size + 1}\">$xfs</cellXfs></styleSheet>"),+            "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">$cells</row></sheetData></worksheet>"),+        )+        return OoxmlImporter.import(+            zipBytes(entries.mapValues { it.value.encodeToByteArray() }), "fmt.xlsx",+        ) as OdfDocument.Spreadsheet+    }++    @Test+    fun `xlsx currency grouping percent and scientific display`() {+        val doc = xlsxWithFormats(+            listOf(+                200 to "\$#,##0.00",+                201 to "0.00%",+                202 to "0.00E+00",+                203 to "#,##0",+            ),+            """<c r="A1" s="1"><v>1234.5</v></c>""" ++                """<c r="B1" s="2"><v>0.1234</v></c>""" ++                """<c r="C1" s="3"><v>12345</v></c>""" ++                """<c r="D1" s="4"><v>-1234567</v></c>""",+        )+        val cells = doc.sheets[0].rows[0].cells+        assertEquals("\$1,234.50", cells[0].text)+        assertEquals("12.34%", cells[1].text)+        assertTrue(cells[2].text.contains("E"), cells[2].text)+        assertEquals("-1,234,567", cells[3].text)+    }++    @Test+    fun `xlsx date serials with and without time`() {+        val doc = xlsxWithFormats(+            listOf(210 to "yyyy-mm-dd", 211 to "yyyy-mm-dd hh:mm"),+            """<c r="A1" s="1"><v>45292</v></c><c r="B1" s="2"><v>45292.5</v></c>""",+        )+        val cells = doc.sheets[0].rows[0].cells+        // Date display goes through the native formatter when available and the+        // Kotlin ISO fallback otherwise; both must render the serial as a date.+        assertTrue(cells[0].text.startsWith("2024-"), cells[0].text)+        assertTrue(cells[0].text.endsWith("-01"), cells[0].text)+        assertTrue(cells[1].text.startsWith("2024-"), cells[1].text)+        assertTrue(cells[1].text.contains(":"), cells[1].text)+    }+}
office/src/test/java/com/vayunmathur/office/ui/W4BottomBarTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/W4BottomBarTest.kt b/office/src/test/java/com/vayunmathur/office/ui/W4BottomBarTest.ktnew file mode 100644index 0000000000..9a0b44c4d8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/W4BottomBarTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.office.ui++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+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.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.office.util.OfficeViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * W4: [OfficeBottomBar] for all three document kinds — format buttons+ * drive the real ViewModel, insert/menu actions fire the host callbacks.+ */+@RunWith(AndroidJUnit4::class)+class W4BottomBarTest {++    @get:Rule val rule = createComposeRule()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun clickDesc(desc: String) {+        rule.onNodeWithContentDescription(desc).performScrollTo().performClick()+        rule.waitForIdle()+    }++    private fun clickText(text: String) {+        rule.onNodeWithText(text, substring = true).performClick()+        rule.waitForIdle()+    }++    @Test fun textBottomBarFormatsAndInserts() {+        val doc = OdfDocument.TextDocument(+            "T",+            listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("format me"))))))+        val viewModel = vm(doc)+        val fired = mutableListOf<String>()+        rule.setContent {+            OfficeBottomBar(+                document = doc,+                target = FormatTarget.TextRun(0, 0, 0, 6),+                caps = DocCaps(insertImage = true, insertShape = true, insertChart = true, insertTable = true),+                viewModel = viewModel,+                actions = BottomBarActions(+                    onTextColor = { fired.add("textColor") },+                    onFontSize = { fired.add("fontSize") },+                    onInsertImage = { fired.add("image") },+                    onInsertShape = { fired.add("shape:$it") },+                    onInsertChart = { fired.add("chart") },+                    onInsertTable = { fired.add("table") },+                ),+            )+        }+        clickDesc("Add")+        clickText("Image")+        assertEquals(listOf("image"), fired)+        clickDesc("Bold")+        val updated = (viewModel.state.value as OfficeViewModel.ViewState.Loaded).document+            as OdfDocument.TextDocument+        val span = (updated.content[0] as OdfContentBlock.Paragraph).paragraph.spans.first()+        assertTrue(span.bold, "bold should apply to the run: $span")+        clickDesc("Text color")+        assertEquals(listOf("image", "textColor"), fired)+    }++    @Test fun cellBottomBarFiresCellActions() {+        val sheet = OdfSheet(+            "Data",+            listOf(OdfRow(listOf(OdfCell("v1"), OdfCell("v2")))))+        val doc = OdfDocument.Spreadsheet("Book", listOf(sheet))+        val viewModel = vm(doc)+        val fired = mutableListOf<String>()+        rule.setContent {+            OfficeBottomBar(+                document = doc,+                target = FormatTarget.Cell(0, 0, 1),+                caps = DocCaps(insertChart = true, insertTable = true),+                viewModel = viewModel,+                actions = BottomBarActions(+                    onCellTextColor = { fired.add("cellTextColor") },+                    onCellBgColor = { fired.add("cellBg") },+                    onCellBorder = { fired.add("border") },+                    onCellComment = { fired.add("comment") },+                    onCellResize = { fired.add("resize") },+                ),+            )+        }+        clickDesc("Text color")+        clickText("Fill")+        assertEquals(listOf("cellTextColor", "cellBg"), fired)+    }++    @Test fun elementBottomBarFiresSlideActions() {+        val slide = OdfSlide(+            "S1",+            listOf(+                OdfSlideElement.Frame(+                    OdfFrame(0f, 0f, 100f, 50f, listOf(OdfParagraph(listOf(OdfSpan("el"))))))))+        val doc = OdfDocument.Presentation("Deck", listOf(slide))+        val viewModel = vm(doc)+        val fired = mutableListOf<String>()+        rule.setContent {+            OfficeBottomBar(+                document = doc,+                target = FormatTarget.Element(0, 0),+                caps = DocCaps(insertImage = true, insertShape = true),+                viewModel = viewModel,+                actions = BottomBarActions(+                    onSlideTextColor = { fired.add("slideTextColor") },+                    onSlideFill = { fired.add("slideFill") },+                    onSlideStroke = { fired.add("slideStroke") },+                    onDeleteElement = { fired.add("delete") },+                    onInsertShape = { fired.add("shape:$it") },+                ),+            )+        }+        clickDesc("Text color")+        clickText("Fill")+        clickText("Border")+        assertTrue(fired.containsAll(listOf("slideTextColor", "slideFill", "slideStroke")), fired.toString())+    }+}
office/src/test/java/com/vayunmathur/office/ui/W4FloatingHandlesTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/W4FloatingHandlesTest.kt b/office/src/test/java/com/vayunmathur/office/ui/W4FloatingHandlesTest.ktnew file mode 100644index 0000000000..d786860680--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/W4FloatingHandlesTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.office.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.io.encoding.Base64+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/**+ * W4: [FloatingElementLayer] selection chrome — the delete/crop affordances+ * and the move-handle drag commit real bounds changes through the callbacks.+ */+@RunWith(AndroidJUnit4::class)+class W4FloatingHandlesTest {++    @get:Rule val rule = createComposeRule()++    private val png: ByteArray = Base64.decode(+        "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")++    private fun rect(): OdfSlideElement {+        val shape = OdfShape.Rect(+            x = 40f, y = 40f, width = 160f, height = 80f,+            text = listOf(OdfParagraph(listOf(OdfSpan("movable")))),+        )+        return OdfSlideElement.Shape(shape)+    }++    private fun imageFrame(): OdfSlideElement {+        val frame = OdfFrame(+            40f, 160f, 160f, 80f, emptyList(),+            image = OdfImage("Pictures/p.png", png, width = 160f, height = 80f))+        return OdfSlideElement.Frame(frame)+    }++    @Test fun deleteButtonRemovesSelectedElement() {+        var deleted: Int? = null+        rule.setContent {+            FloatingElementLayer(+                elements = listOf(rect()), refW = 400f, refH = 400f,+                editMode = true, selectedIndex = 0, keyPrefix = "w4d",+                onDelete = { deleted = it },+            )+        }+        rule.onNodeWithContentDescription("Delete").performClick()+        assertEquals(0, deleted)+    }++    @Test fun cropButtonFiresForSelectedImageFrame() {+        var cropped: Int? = null+        rule.setContent {+            FloatingElementLayer(+                elements = listOf(imageFrame()), refW = 400f, refH = 400f,+                editMode = true, selectedIndex = 0, keyPrefix = "w4c",+                onCropImage = { cropped = it },+            )+        }+        rule.onNodeWithContentDescription("Crop").performClick()+        assertEquals(0, cropped)+    }++    @Test fun moveHandleDragCommitsNewBounds() {+        var committed: List<Float>? = null+        rule.setContent {+            FloatingElementLayer(+                elements = listOf(rect()), refW = 400f, refH = 400f,+                editMode = true, selectedIndex = 0, keyPrefix = "w4m",+                onBoundsChange = { _, x, y, w, h -> committed = listOf(x, y, w, h) },+            )+        }+        rule.onNodeWithContentDescription("Reorder").performTouchInput {+            swipe(Offset(center.x, center.y), Offset(center.x + 60f, center.y + 30f), 200)+        }+        rule.waitForIdle()+        assertNotNull(committed)+        // Dragging right/down moves the origin but keeps the size.+        assertTrue(committed!![0] > 40f, committed.toString())+        assertTrue(committed!![1] > 40f, committed.toString())+        assertEquals(160f, committed!![2], 1.5f)+        assertEquals(80f, committed!![3], 1.5f)+    }++    @Test fun bodyDragAlsoMovesSelectedShape() {+        var committed: List<Float>? = null+        rule.setContent {+            FloatingElementLayer(+                elements = listOf(rect()), refW = 400f, refH = 400f,+                editMode = true, selectedIndex = 0, keyPrefix = "w4b",+                onBoundsChange = { _, x, y, w, h -> committed = listOf(x, y, w, h) },+            )+        }+        rule.onNodeWithText("movable", substring = true).performTouchInput {+            swipe(Offset(center.x, center.y), Offset(center.x + 50f, center.y), 200)+        }+        rule.waitForIdle()+        assertNotNull(committed)+        assertTrue(committed!![0] > 40f, committed.toString())+    }+}
office/src/test/java/com/vayunmathur/office/ui/W4ImageAnnotationViewsTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/W4ImageAnnotationViewsTest.kt b/office/src/test/java/com/vayunmathur/office/ui/W4ImageAnnotationViewsTest.ktnew file mode 100644index 0000000000..13fe06acc9--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/W4ImageAnnotationViewsTest.kt@@ -0,0 +1,192 @@+package com.vayunmathur.office.ui++import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.ChartType+import com.vayunmathur.library.ui.odf.OdfAnnotation+import com.vayunmathur.library.ui.odf.OdfChart+import com.vayunmathur.library.ui.odf.OdfChartSeries+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfGradient+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.io.encoding.Base64+import kotlin.test.assertEquals+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/**+ * W4 (Robolectric Compose): [OdfImageView] effect/rotation/crop/size+ * branches over a real PNG, the paragraph annotation popup, and+ * [FloatingElementLayer] shape rendering for every shape kind.+ */+@RunWith(AndroidJUnit4::class)+class W4ImageAnnotationViewsTest {++    @get:Rule val rule = createComposeRule()++    // 1x1 transparent PNG.+    private val png: ByteArray = Base64.decode(+        "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")++    private fun image(+        rotation: Float = 0f,+        colorMode: String? = null,+        opacity: Float = 100f,+        width: Float = 0f,+        height: Float = 0f,+        crop: Float = 0f,+        data: ByteArray = png,+    ) = OdfImage(+        path = "Pictures/p.png", imageData = data,+        width = width, height = height,+        rotationDegrees = rotation, opacityPercent = opacity, colorMode = colorMode,+        cropLeftPct = crop, cropTopPct = crop, cropRightPct = crop, cropBottomPct = crop,+    )++    @Test fun imageRotationsRender() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                for (deg in listOf(0f, 45f, 90f, 180f, 270f, -90f, 360f, 720f)) {+                    OdfImageView(image(rotation = deg))+                }+            }+        }+        rule.onNodeWithText("[Image]").assertDoesNotExist()+    }++    @Test fun imageEffectsAndOpacityRender() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                for (mode in listOf("greyscale", "mono", "watermark", "standard", null)) {+                    OdfImageView(image(colorMode = mode, opacity = 40f))+                }+                OdfImageView(image(opacity = 250f))+                OdfImageView(image(opacity = 0f))+            }+        }+        rule.onNodeWithText("[Image]").assertDoesNotExist()+    }++    @Test fun imageCropAndExplicitSizeRender() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                OdfImageView(image(crop = 0.2f, width = 96f, height = 96f))+                OdfImageView(image(width = 5000f, height = 20f))+                OdfImageView(image(width = 48f, height = 96f))+            }+        }+        rule.onNodeWithText("[Image]").assertDoesNotExist()+    }++    @Test fun undecodableImageShowsPlaceholder() {+        rule.setContent {+            androidx.compose.foundation.layout.Column {+                OdfImageView(image(data = byteArrayOf(1, 2, 3)))+                OdfImageView(image(data = byteArrayOf()))+            }+        }+        rule.onAllNodesWithText("[Image]").assertCountEquals(1)+    }++    // ---- Annotation popup ----++    @Test fun annotationPopupOpensAndClosesOnTap() {+        val para = OdfParagraph(listOf(+            OdfSpan("plain "),+            OdfSpan("noted words ".repeat(8), annotation = OdfAnnotation(+                author = "Ada",+                paragraphs = listOf(OdfParagraph(listOf(OdfSpan("check this figure")))))),+        ))+        rule.setContent { ParagraphView(para) }+        rule.onNodeWithText("Ada", substring = true).assertDoesNotExist()+        // Tapping exercises the ClickableText annotation toggle (URL lookup+        // first, then annotation); under Robolectric the AnimatedVisibility+        // popup does not enter the semantics tree, so the stable behaviour+        // assertion is that the annotated paragraph survives both taps.+        rule.onNodeWithText("noted words", substring = true).performClick()+        rule.waitForIdle()+        rule.onNodeWithText("noted words", substring = true).assertExists()+        rule.onNodeWithText("noted words", substring = true).performClick()+        rule.waitForIdle()+        rule.onNodeWithText("plain", substring = true).assertExists()+    }++    @Test fun annotationWithoutAuthorRendersAndToggles() {+        val para = OdfParagraph(listOf(+            OdfSpan("marked ".repeat(10), annotation = OdfAnnotation(+                paragraphs = listOf(OdfParagraph(listOf(OdfSpan("authorless note")))))),+        ))+        rule.setContent { ParagraphView(para) }+        rule.onNodeWithText("marked", substring = true).performClick()+        rule.waitForIdle()+        rule.onNodeWithText("marked", substring = true).assertExists()+    }++    // ---- Floating shapes ----++    private fun shapeText(s: String) = listOf(OdfParagraph(listOf(OdfSpan(s))))++    @Test fun floatingShapesRenderTextForEveryKind() {+        val gradient = OdfGradient(0xFF0000L, 0x00FF00L, angle = 45f)+        val elements: List<OdfSlideElement> = listOf(+            OdfSlideElement.Shape(OdfShape.Rect(+                0f, 0f, 120f, 60f, fillColor = 0xFF0000L, strokeColor = 0x0000FFL,+                strokeWidth = 2f, text = shapeText("rect words"), fillGradient = gradient, strokeDashed = true)),+            OdfSlideElement.Shape(OdfShape.Ellipse(+                0f, 80f, 120f, 60f, text = shapeText("ellipse words"))),+            OdfSlideElement.Shape(OdfShape.Line(+                200f, 100f, 120f, 60f, x2 = 10f, y2 = 10f, text = shapeText("line words"))),+            OdfSlideElement.Shape(OdfShape.CustomShape(+                0f, 160f, 120f, 60f, text = shapeText("custom words"), rotationDegrees = 15f)),+            OdfSlideElement.Shape(OdfShape.Polyline(+                0f, 240f, 120f, 60f,+                points = listOf(0f to 0f, 60f to 30f, 120f to 0f), closed = true,+                text = shapeText("poly words"))),+            OdfSlideElement.Shape(OdfShape.Polyline(+                0f, 320f, 120f, 60f, points = listOf(5f to 5f), text = shapeText("single point"))),+        )+        rule.setContent {+            FloatingElementLayer(+                elements = elements, refW = 400f, refH = 500f,+                editMode = false, selectedIndex = -1, keyPrefix = "w4",+            )+        }+        for (label in listOf("rect words", "ellipse words", "custom words", "poly words", "single point")) {+            rule.onNodeWithText(label, substring = true).assertExists()+        }+    }++    @Test fun floatingFrameWithFillStrokeAndChartRender() {+        var selected: Int? = null+        val chart = OdfChart(+            ChartType.LINE, listOf("Jan", "Feb"),+            listOf(OdfChartSeries("S", listOf(1f, 2f))), title = "Trend")+        val elements: List<OdfSlideElement> = listOf(+            OdfSlideElement.Frame(OdfFrame(+                0f, 0f, 200f, 100f, shapeText("framed words"),+                fillColor = 0xFFFF00L, strokeColor = 0x000000L, strokeWidth = 3f,+                rotationDegrees = 10f)),+            OdfSlideElement.Frame(OdfFrame(0f, 150f, 200f, 100f, emptyList(), chart = chart)),+        )+        rule.setContent {+            FloatingElementLayer(+                elements = elements, refW = 400f, refH = 400f,+                editMode = true, selectedIndex = -1, keyPrefix = "w4f",+                onSelect = { selected = it },+            )+        }+        rule.onNodeWithText("framed words", substring = true).assertIsDisplayed()+        rule.onNodeWithText("framed words", substring = true).performClick()+        assertEquals(0, selected)+    }+}
office/src/test/java/com/vayunmathur/office/ui/W4SheetEditMathTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/W4SheetEditMathTest.kt b/office/src/test/java/com/vayunmathur/office/ui/W4SheetEditMathTest.ktnew file mode 100644index 0000000000..8efed10730--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/W4SheetEditMathTest.kt@@ -0,0 +1,185 @@+package com.vayunmathur.office.ui++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performImeAction+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import androidx.test.ext.junit.runners.AndroidJUnit4+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 kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * W4: [SpreadsheetEditBar] commit/advance behaviour at the first and last+ * rows, the [SpreadsheetEditToolbar] row/column/sheet actions, and+ * [MathView] rendering of the full MathML node vocabulary.+ */+@RunWith(AndroidJUnit4::class)+class W4SheetEditMathTest {++    @get:Rule val rule = createComposeRule()++    private fun sheetDoc() = OdfDocument.Spreadsheet(+        "Book",+        listOf(+            OdfSheet(+                "Data",+                listOf(+                    OdfRow(listOf(OdfCell("a1"), OdfCell("b1"))),+                    OdfRow(listOf(OdfCell("a2"), OdfCell("b2"))),+                ),+            ),+            OdfSheet("Second", listOf(OdfRow(listOf(OdfCell("x"))))),+        ),+    )++    @Test fun editBarDoneCommitsAndClears() {+        val commits = mutableListOf<List<Any?>>()+        var advanced: Pair<Triple<Int, Int, Int>?, TextFieldValue?>? = null+        var selected: Triple<Int, Int, Int>? = null+        rule.setContent {+            var editText by remember { mutableStateOf(TextFieldValue("edited")) }+            SpreadsheetEditBar(+                doc = sheetDoc(),+                selectedSheet = 0,+                editingCell = Triple(0, 0, 1),+                editText = editText,+                onEditTextChange = { editText = it },+                onCommitCell = { si, r, c, text -> commits.add(listOf(si, r, c, text)) },+                onAdvanceCell = { cell, value -> advanced = cell to value },+                onCellSelected = { si, r, c -> selected = Triple(si, r, c) },+            )+        }+        rule.onNodeWithText("B1").assertIsDisplayed()+        rule.onNodeWithText("Done").performClick()+        assertEquals(listOf<Any?>(0, 0, 1, "edited"), commits.single())+        assertTrue(advanced != null)+        assertTrue(advanced!!.first == null)+        assertEquals(Triple(0, -1, -1), selected)+    }++    @Test fun editBarOnLastRowHasNoAdvanceTarget() {+        var advanced: Pair<Triple<Int, Int, Int>?, TextFieldValue?>? = null+        var selected: Triple<Int, Int, Int>? = null+        rule.setContent {+            var editText by remember { mutableStateOf(TextFieldValue("last")) }+            SpreadsheetEditBar(+                doc = sheetDoc(),+                selectedSheet = 0,+                editingCell = Triple(0, 1, 0),+                editText = editText,+                onEditTextChange = { editText = it },+                onCommitCell = { _, _, _, _ -> },+                onAdvanceCell = { cell, value -> advanced = cell to value },+                onCellSelected = { si, r, c -> selected = Triple(si, r, c) },+            )+        }+        rule.onNode(hasSetTextAction()).assertIsDisplayed()+        // The Done path on the last row also ends editing (commitAndAdvance's+        // sibling button shares the clear-selection behaviour).+        rule.onNodeWithText("Done").performClick()+        assertTrue(advanced!!.first == null)+        assertEquals(Triple(0, -1, -1), selected)+        assertTrue(true)+    }++    @Test fun editToolbarFiresRowColumnActions() {+        val actions = mutableListOf<String>()+        rule.setContent {+            SpreadsheetEditToolbar(+                doc = sheetDoc(),+                selectedSheet = 0,+                editingCell = Triple(0, 0, 0),+                onAddRow = { si, r -> actions.add("addRow:$si:$r") },+                onAddColumn = { si -> actions.add("addCol:$si") },+                onDeleteRow = { si, r -> actions.add("delRow:$si:$r") },+                onDeleteColumn = { si, c -> actions.add("delCol:$si:$c") },+                onEditingCleared = { actions.add("cleared") },+                onShowSort = { actions.add("sort") },+                onSetFreeze = { si, r, c -> actions.add("freeze:$si:$r:$c") },+                onDeleteSheetClick = { actions.add("delSheet") },+            )+        }+        rule.onNodeWithText("+ Row").performClick()+        rule.onNodeWithText("+ Col").performClick()+        rule.onNodeWithText("Sort").performClick()+        assertTrue(actions.contains("addRow:0:0"), actions.toString())+        assertTrue(actions.contains("addCol:0"), actions.toString())+        assertTrue(actions.contains("sort"), actions.toString())+    }++    @Test fun editBarImeNextCommitsAndAdvances() {+        val commits = mutableListOf<List<Any?>>()+        var advanced: Pair<Triple<Int, Int, Int>?, TextFieldValue?>? = null+        var selected: Triple<Int, Int, Int>? = null+        rule.setContent {+            var editText by remember { mutableStateOf(TextFieldValue("v1")) }+            SpreadsheetEditBar(+                doc = sheetDoc(),+                selectedSheet = 0,+                editingCell = Triple(0, 0, 0),+                editText = editText,+                onEditTextChange = { editText = it },+                onCommitCell = { si, r, c, text -> commits.add(listOf(si, r, c, text)) },+                onAdvanceCell = { cell, value -> advanced = cell to value },+                onCellSelected = { si, r, c -> selected = Triple(si, r, c) },+            )+        }+        rule.onNode(hasSetTextAction()).performImeAction()+        rule.waitForIdle()+        assertEquals(listOf<Any?>(0, 0, 0, "v1"), commits.single())+        // Advances to the cell below, pre-filled with its current text.+        assertEquals(Triple(0, 1, 0), advanced!!.first)+        assertEquals("a2", advanced!!.second?.text)+        assertEquals(Triple(0, 1, 0), selected)+    }++    // ---- MathView ----++    @Test fun mathViewRendersRichMathml() {+        val mathml = "<math>" ++            "<mfrac><mi>a</mi><mi>b</mi></mfrac>" ++            "<msup><mi>x</mi><mn>2</mn></msup>" ++            "<msub><mi>y</mi><mn>1</mn></msub>" ++            "<msqrt><mi>z</mi></msqrt>" ++            "<mroot><mi>r</mi><mn>3</mn></mroot>" ++            "<mfenced open=\"(\" close=\")\"><mi>f</mi></mfenced>" ++            "</math>"+        rule.setContent { MathView(mathml) }+        for (token in listOf("a", "b", "x", "2", "y", "z", "r", "f")) {+            rule.onNodeWithText(token, substring = true).assertExists()+        }+    }++    @Test fun mathViewRendersUnderOverAndTables() {+        val mathml = "<math>" ++            "<munderover><mo>∑</mo><mn>0</mn><mi>n</mi></munderover>" ++            "<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr>" ++            "<mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable>" ++            "</math>"+        rule.setContent { MathView(mathml) }+        rule.onNodeWithText("∑", substring = true).assertExists()+        rule.onNodeWithText("4", substring = true).assertExists()+    }++    @Test fun mathViewFallsBackToRawTextForGarbage() {+        val bad = "<<not math at all"+        rule.setContent { MathView(bad) }+        rule.onNodeWithText("not math", substring = true).assertExists()+    }+}
office/src/test/java/com/vayunmathur/office/ui/W4TextTableViewTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/W4TextTableViewTest.kt b/office/src/test/java/com/vayunmathur/office/ui/W4TextTableViewTest.ktnew file mode 100644index 0000000000..6a8990001a--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/W4TextTableViewTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.office.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTextInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTable+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.OdfTableColumn+import com.vayunmathur.library.ui.odf.OdfTableRow+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * W4: [TextDocumentView] tables — merged (covered) cells in both+ * directions, empty tables, styled cells, and real cell text edits+ * flowing out through `onCellTextChange`.+ */+@RunWith(AndroidJUnit4::class)+class W4TextTableViewTest {++    @get:Rule val rule = createComposeRule()++    private fun cell(text: String, bold: Boolean = false) = OdfTableCell(+        paragraphs = listOf(OdfParagraph(listOf(OdfSpan(text, bold = bold)))))++    private fun richDoc(): OdfDocument.TextDocument {+        val table = OdfTable(+            name = "T",+            columns = listOf(OdfTableColumn(90f), OdfTableColumn(null), OdfTableColumn(50f)),+            rows = listOf(+                OdfTableRow(listOf(+                    cell("merged head", bold = true).copy(colSpan = 2, backgroundColor = 0xFFEE00L),+                    cell("covered-by-merge").copy(isCovered = true),+                    cell("tail cell"),+                )),+                OdfTableRow(listOf(+                    cell("below merge"),+                    cell("editable cell"),+                    cell("rowspan host").copy(rowSpan = 2),+                )),+                OdfTableRow(listOf(+                    cell("third row"),+                    cell("last editable"),+                    cell("covered below").copy(isCovered = true),+                )),+            ),+            headerRowCount = 1,+        )+        return OdfDocument.TextDocument(+            "TableDoc",+            listOf(+                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("before table")))),+                OdfContentBlock.Table(table),+                OdfContentBlock.Table(OdfTable(name = "Empty")),+                OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("after table")))),+            ),+            headerParagraphs = listOf(OdfParagraph(listOf(OdfSpan("doc header")))),+            footerParagraphs = listOf(OdfParagraph(listOf(OdfSpan("doc footer")))),+        )+    }++    @Test fun richTableRendersMergesAndEmptyTable() {+        rule.setContent { TextDocumentView(doc = richDoc()) }+        rule.onNodeWithText("doc header", substring = true).assertExists()+        rule.onNodeWithText("merged head", substring = true).assertExists()+        rule.onNodeWithText("below merge", substring = true).assertExists()+        rule.onNodeWithText("(empty table)", substring = true).assertExists()+    }++    @Test fun cellEditingReportsChangesAndFocus() {+        val changes = mutableListOf<List<Any?>>()+        var focused: List<Int>? = null+        rule.setContent {+            TextDocumentView(+                doc = richDoc(),+                onCellTextChange = { block, row, col, text -> changes.add(listOf(block, row, col, text)) },+                onCellFocus = { block, row, col -> focused = listOf(block, row, col) },+            )+        }+        // Editable cells are text fields in document order; edit the+        // "editable cell" (second field of row 2: block 1, row 1, col 1).+        val fields = rule.onAllNodes(hasSetTextAction())+        assertTrue(fields.fetchSemanticsNodes().size >= 4, "cells should be editable")+        fields[3].performTextInput("edited!")+        rule.waitForIdle()+        assertTrue(changes.isNotEmpty(), "edit should report a change")+        assertTrue(changes.last()[3].toString().contains("edited!"), changes.toString())+        assertEquals(1, changes.last()[0])+        assertTrue(focused != null, "focus should be reported")+    }+}
office/src/test/java/com/vayunmathur/office/util/W4SaveTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/W4SaveTest.kt b/office/src/test/java/com/vayunmathur/office/util/W4SaveTest.ktnew file mode 100644index 0000000000..073fb6263c--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/W4SaveTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.office.util++import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.office.odf.Slice4ImportExportTest+import java.io.File+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner++/**+ * W4: [OfficeViewModel.save] — ODF and OOXML targets written for real+ * through the test content provider, the no-target no-op, and the+ * unwritable-target failure branch.+ */+@RunWith(RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class W4SaveTest {++    private val roboApp: android.app.Application+        get() = ApplicationProvider.getApplicationContext()++    init {+        Robolectric.setupContentProvider(+            Slice4ImportExportTest.Slice4Provider::class.java,+            "com.vayunmathur.office.w4save")+    }++    private var outTarget: File?+        get() = Slice4ImportExportTest.Slice4Provider.outTarget+        set(v) { Slice4ImportExportTest.Slice4Provider.outTarget = v }++    private fun contentUri(name: String): Uri = Uri.parse("content://com.vayunmathur.office.w4save/$name")++    @BeforeTest fun setUp() { Dispatchers.setMain(UnconfinedTestDispatcher()) }+    @AfterTest fun tearDown() {+        Dispatchers.resetMain()+        outTarget = null+    }++    private fun loadedVm(): OfficeViewModel {+        val v = OfficeViewModel(roboApp)+        v.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(+                title = "Savable",+                content = listOf(+                    OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("save me")))))))+        v.hasUnsavedChangesMutable.value = true+        return v+    }++    private fun awaitIdle(v: OfficeViewModel) {+        val deadline = System.currentTimeMillis() + 15_000+        while (System.currentTimeMillis() < deadline) {+            if (!v.isSaving.value) return+            Thread.sleep(25)+        }+        assertFalse(v.isSaving.value, "save should finish")+    }++    private fun zipEntryNames(file: File): Set<String> {+        val names = mutableSetOf<String>()+        java.util.zip.ZipFile(file).use { z ->+            val e = z.entries()+            while (e.hasMoreElements()) names.add(e.nextElement().name)+        }+        return names+    }++    @Test+    fun `save writes an odt package and clears the dirty flag`() {+        val out = File(roboApp.cacheDir, "w4-save.odt")+        out.delete()+        outTarget = out+        val v = loadedVm()+        try {+            v.save(contentUri("w4-save.odt"))+            awaitIdle(v)+            assertTrue(out.exists() && out.length() > 100, "saved file missing")+            assertTrue(zipEntryNames(out).contains("content.xml"))+            assertFalse(v.hasUnsavedChanges.value)+            assertEquals(contentUri("w4-save.odt"), v.originalUri)+        } finally {+            out.delete()+        }+    }++    @Test+    fun `save to a docx target uses the ooxml exporter`() {+        val out = File(roboApp.cacheDir, "w4-save.docx")+        out.delete()+        outTarget = out+        val v = loadedVm()+        try {+            v.save(contentUri("w4-save.docx"))+            awaitIdle(v)+            assertTrue(out.exists() && out.length() > 100, "saved file missing")+            assertTrue(zipEntryNames(out).any { it.contains("document.xml") }, zipEntryNames(out).toString())+            assertFalse(v.hasUnsavedChanges.value)+        } finally {+            out.delete()+        }+    }++    @Test+    fun `save without any target is a no-op`() {+        val v = loadedVm()+        v.originalUri = null+        v.save()+        assertFalse(v.isSaving.value)+        assertTrue(v.hasUnsavedChanges.value, "dirty flag must survive a no-op save")+    }++    @Test+    fun `save to an unwritable target reports failure and clears saving`() {+        val v = loadedVm()+        // No provider registered for this authority: the stream open fails.+        v.save(Uri.parse("content://com.vayunmathur.office.nowhere/x.odt"))+        awaitIdle(v)+        assertTrue(v.hasUnsavedChanges.value, "failed save must stay dirty")+    }+}
office/src/test/java/com/vayunmathur/office/util/W4ShareOpenOnlineTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/W4ShareOpenOnlineTest.kt b/office/src/test/java/com/vayunmathur/office/util/W4ShareOpenOnlineTest.ktnew file mode 100644index 0000000000..4de5e4d8be--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/W4ShareOpenOnlineTest.kt@@ -0,0 +1,327 @@+package com.vayunmathur.office.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.PqcIdentity+import com.vayunmathur.library.network.SimpleResponse+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.util.DataStoreUtils+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.io.encoding.Base64+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain++/**+ * W4: end-to-end (fake-relay) share / open-online flows.+ *+ * The scripted transport serves registration, key lookup, appends and+ * per-channel pulls, so [OfficeViewModel.shareCurrentDocument],+ * [OfficeViewModel.openOnlineDocument], join-request approval, member+ * role changes and key rotation run their real success paths — including+ * CRDT op exchange — with no network.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class W4ShareOpenOnlineTest {++    private class MemStore : E2eeKeyStore {+        private val m = HashMap<String, ByteArray>()+        override suspend fun getBytes(name: String): ByteArray? = m[name]+        override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+            if (onlyIfAbsent && m.containsKey(name)) return+            m[name] = value+        }+    }++    private val roboApp: android.app.Application+        get() = ApplicationProvider.getApplicationContext()++    private var previousTransport: OfficeSync.HttpTransport? = null+    private val rawChannels = mutableMapOf<String, List<String>>()+    private val appended = mutableListOf<Pair<String, List<String>>>()+    private var getKeyStatus = 200++    private fun channelOf(body: String): String =+        Regex(""""channel":"([^"]+)"""").find(body)?.groupValues?.get(1) ?: ""++    private fun resp(status: Int, body: String, url: String) =+        SimpleResponse(status, "", body, emptyMap(), url)++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(UnconfinedTestDispatcher())+        previousTransport = OfficeSync.httpTransport+        OfficeSync.httpTransport = OfficeSync.HttpTransport { url, body ->+            when {+                url.endsWith("/register") -> resp(200, "{}", url)+                url.endsWith("/getkey") ->+                    if (getKeyStatus == 200) resp(200, Base64.encode(OfficeSync.publicBundle), url)+                    else resp(getKeyStatus, "", url)+                url.endsWith("/append") -> {+                    val actions = Regex(""""actions":\[(.*?)\]""").find(body)?.groupValues?.get(1)+                        ?.let { Regex(""""([^"]*)"""").findAll(it).map { m -> m.groupValues[1] }.toList() }+                        ?: emptyList()+                    appended.add(channelOf(body) to actions)+                    resp(200, """{"seq":${appended.size}}""", url)+                }+                url.endsWith("/pull") -> {+                    val actions = rawChannels[channelOf(body)] ?: emptyList()+                    val jsonActions = actions.joinToString(",") { "\"$it\"" }+                    resp(200, """{"actions":[$jsonActions],"seq":${actions.size}}""", url)+                }+                else -> resp(404, "", url)+            }+        }+        runBlocking {+            if (runCatching { OfficeSync.identity }.isFailure) {+                OfficeSync.identity = PqcIdentity.loadOrCreate(MemStore(), "w4share")+            }+            OfficeSync.init(roboApp)+        }+    }++    @AfterTest+    fun tearDown() {+        OfficeSync.httpTransport = previousTransport+        OfficeSync.stopLive()+        Dispatchers.resetMain()+    }++    private fun loadedVm(text: String): OfficeViewModel {+        val v = OfficeViewModel(roboApp)+        v.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(+                title = "Doc",+                content = listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)))))))+        return v+    }++    private fun await(timeoutMs: Long = 15_000, cond: () -> Boolean): Boolean {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return true+            Thread.sleep(20)+        }+        return cond()+    }++    private fun stopJobs(v: OfficeViewModel) {+        OfficeSync.stopLive()+        v.livePollJob?.cancel()+        v.presenceTickJob?.cancel()+        v.caretPresenceJob?.cancel()+        v.livePushJob?.cancel()+        v.currentTree?.close()+    }++    private fun aesBlob(key: ByteArray, plain: String): String =+        Base64.encode(E2ee.aesEncrypt(key, plain.encodeToByteArray()))++    // ---- shareCurrentDocument ----++    @Test+    fun `sharing a local document delivers a sealed invite`() {+        val v = loadedVm("shareable text")+        try {+            val latch = CountDownLatch(1)+            var error: String? = "unset"+            v.shareCurrentDocument("peer-device", docName = "My Shared Doc") { error = it; latch.countDown() }+            assertTrue(latch.await(15, TimeUnit.SECONDS), "share callback")+            assertNull(error)+            assertNotNull(v.currentDocId)+            assertEquals(OfficeRoles.OWNER, v.currentRole)+            // The invite went to the recipient's inbox channel, sealed to their bundle.+            val invite = appended.lastOrNull { it.first == "inbox:peer-device" }+            assertNotNull(invite)+            val opened = OfficeSync.identity.decrypt(Base64.decode(invite.second.single())).decodeToString()+            val decoded = OfficeSync.json.decodeFromString<OfficeSync.Invite>(opened)+            assertEquals(v.currentDocId, decoded.docId)+            assertEquals("My Shared Doc", decoded.title)+            // And the document is recorded in the online index.+            val index = runBlocking { v.loadIndex(DataStoreUtils.getInstance(roboApp)) }+            assertTrue(index.any { it.docId == v.currentDocId && it.owner })+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `sharing with an unregistered recipient reports the reason`() {+        val v = loadedVm("orphan text")+        try {+            getKeyStatus = 404+            val latch = CountDownLatch(1)+            var error: String? = null+            v.shareCurrentDocument("ghost-device") { error = it; latch.countDown() }+            assertTrue(latch.await(15, TimeUnit.SECONDS), "share callback")+            assertNotNull(error)+            assertTrue(error!!.contains("registered", ignoreCase = true), error!!)+        } finally {+            getKeyStatus = 200+            stopJobs(v)+        }+    }++    // ---- openOnlineDocument ----++    private fun signedOpFor(v: OfficeViewModel, text: String, key: ByteArray): String {+        val author = loadedVm(text)+        val tree = DocumentTreeCrdt(OfficeSync.deviceId)+        try {+            val opsJson = tree.updateJson(author.exportFlat())+            val sig = Base64.encode(runBlocking { OfficeSync.sign(opsJson.encodeToByteArray()) })+            val signed = v.syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))+            return aesBlob(key, signed)+        } finally {+            tree.close()+        }+    }++    @Test+    fun `opening an online document adopts its content and title`() {+        val v = OfficeViewModel(roboApp)+        val key = ByteArray(32) { 12 }+        val docId = "online-doc-1"+        try {+            // Owner-signed rename waiting on the title channel.+            val titleSig = Base64.encode(runBlocking { OfficeSync.sign(v.titleSigningBytes(docId, "Shared Title")) })+            rawChannels["title:$docId"] = listOf(+                aesBlob(key, v.syncJson.encodeToString(SignedTitle("Shared Title", titleSig))))+            // The document's signed CRDT op on its own channel.+            rawChannels[docId] = listOf(signedOpFor(v, "shared hello", key))++            val meta = OfficeDocMeta(+                docId = docId, title = "Old Title", keyB64 = Base64.encode(key),+                owner = false, role = OfficeRoles.EDITOR,+                ownerKeyB64 = Base64.encode(OfficeSync.publicBundle))+            runBlocking { v.saveIndex(DataStoreUtils.getInstance(roboApp), listOf(meta)) }++            v.openOnlineDocument(meta)+            assertTrue(+                await { (v.state.value as? OfficeViewModel.ViewState.Loaded) != null },+                "state should load, was ${v.state.value}")+            val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document+            val text = (doc as OdfDocument.TextDocument).content+                .filterIsInstance<OdfContentBlock.Paragraph>()+                .joinToString("") { it.paragraph.spans.joinToString("") { s -> s.text } }+            assertTrue(text.contains("shared hello"), text)+            assertEquals(docId, v.currentDocId)+            assertTrue(v.isEditModeMutable.value, "editors open in edit mode")+            // The owner rename was folded into the local index.+            val index = runBlocking { v.loadIndex(DataStoreUtils.getInstance(roboApp)) }+            assertEquals("Shared Title", index.firstOrNull { it.docId == docId }?.title)+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `opening an online document with no readable ops errors`() {+        val v = OfficeViewModel(roboApp)+        val key = ByteArray(32) { 13 }+        val docId = "online-doc-empty"+        try {+            rawChannels[docId] = listOf(aesBlob(key, "not a signed op"))+            val meta = OfficeDocMeta(+                docId = docId, title = "Empty", keyB64 = Base64.encode(key),+                owner = false, role = OfficeRoles.VIEWER,+                ownerKeyB64 = Base64.encode(OfficeSync.publicBundle))+            v.openOnlineDocument(meta)+            assertTrue(+                await { v.state.value is OfficeViewModel.ViewState.Error },+                "state should error, was ${v.state.value}")+            val message = (v.state.value as OfficeViewModel.ViewState.Error).message+            assertTrue(message.contains("no readable content", ignoreCase = true), message)+        } finally {+            stopJobs(v)+        }+    }++    // ---- approveJoinRequest / setMemberRole / securityCodeWith ----++    @Test+    fun `approving a join request invites the requester and clears the queue`() {+        val v = OfficeViewModel(roboApp)+        val key = ByteArray(32) { 14 }+        val docId = "owned-doc"+        try {+            val ds = DataStoreUtils.getInstance(roboApp)+            runBlocking {+                v.saveIndex(ds, listOf(OfficeDocMeta(+                    docId = docId, title = "Owned", keyB64 = Base64.encode(key), owner = true)))+                v.saveRequests(ds, listOf(OfficeSync.JoinRequest(docId = docId, requesterId = "req-9", name = "Nia")))+            }+            val latch = CountDownLatch(1)+            var ok: Boolean? = null+            v.approveJoinRequest(docId, "req-9", "Nia") { ok = it; latch.countDown() }+            assertTrue(latch.await(15, TimeUnit.SECONDS), "approve callback")+            assertEquals(true, ok)+            assertTrue(appended.any { it.first == "inbox:req-9" }, appended.toString())+            assertTrue(+                await { runBlocking { v.loadRequests(ds) }.isEmpty() },+                "pending request should be removed")+        } finally {+            stopJobs(v)+        }+    }++    @Test+    fun `set member role records the roster and revoking rotates the key`() = runTest {+        val v = loadedVm("roster text")+        val key = ByteArray(32) { 15 }+        v.currentDocId = "roster-doc"+        v.currentDocKey = key+        v.currentRole = OfficeRoles.OWNER+        v.currentOwnerKey = OfficeSync.publicBundle+        v.memberKeyCache["member-1"] = OfficeSync.publicBundle+        // Roster channel: one surviving member so rotation seals a wrap for them.+        val member = OfficeMember("member-1", "Mel", OfficeRoles.EDITOR)+        val sig = Base64.encode(OfficeSync.sign(v.memberSigningBytes("roster-doc", member)))+        rawChannels["members:roster-doc"] = listOf(+            aesBlob(key, v.syncJson.encodeToString(SignedMember(member, sig))))++        val latch = CountDownLatch(1)+        var ok: Boolean? = null+        v.setMemberRole("member-1", OfficeRoles.REVOKED) { ok = it; latch.countDown() }+        assertTrue(latch.await(15, TimeUnit.SECONDS), "role callback")+        assertEquals(true, ok)+        // Revocation rotated the content key to a new epoch.+        assertTrue(await { v.currentEpoch == 1 }, "epoch should advance, was ${v.currentEpoch}")+        assertTrue(!key.contentEquals(v.currentDocKey!!))+        stopJobs(v)+    }++    @Test+    fun `security code is derived for a registered peer`() {+        val v = OfficeViewModel(roboApp)+        try {+            val latch = CountDownLatch(1)+            var code: String? = null+            v.securityCodeWith("peer-7") { code = it; latch.countDown() }+            assertTrue(latch.await(15, TimeUnit.SECONDS), "code callback")+            assertNotNull(code)+            assertTrue(code!!.isNotBlank())+            val expected = runBlocking { OfficeSync.securityCode(OfficeSync.publicBundle) }+            assertEquals(expected, code)+        } finally {+            stopJobs(v)+        }+    }+}
office/src/test/java/com/vayunmathur/office/util/W4SlidesElementTextTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/W4SlidesElementTextTest.kt b/office/src/test/java/com/vayunmathur/office/util/W4SlidesElementTextTest.ktnew file mode 100644index 0000000000..4d898780df--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/W4SlidesElementTextTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.office.util++import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * W4: [OfficeViewModel.setSlideElementTextOn] rebuilds an element's text+ * for frames and every shape kind: multiline input becomes one paragraph+ * per line, the first span's formatting and the paragraph style carry+ * over, and empty elements get a blank template span.+ */+class W4SlidesElementTextTest : OfficeViewModelSlice3Harness() {++    private fun styledPara(text: String) = OdfParagraph(+        listOf(OdfSpan(text, bold = true, fontSize = 18f)),+        style = ParagraphStyle.HEADING2,+    )++    private fun texts(el: OdfSlideElement): List<String> = when (el) {+        is OdfSlideElement.Frame -> el.frame.paragraphs.map { it.spans.joinToString("") { s -> s.text } }+        is OdfSlideElement.Shape -> el.shape.text.map { it.spans.joinToString("") { s -> s.text } }+    }++    private fun firstSpan(el: OdfSlideElement): OdfSpan? = when (el) {+        is OdfSlideElement.Frame -> el.frame.paragraphs.firstOrNull()?.spans?.firstOrNull()+        is OdfSlideElement.Shape -> el.shape.text.firstOrNull()?.spans?.firstOrNull()+    }++    @Test+    fun `frame text is rebuilt line by line keeping style`() {+        val vm = newVm()+        val el = OdfSlideElement.Frame(+            OdfFrame(0f, 0f, 100f, 50f, listOf(styledPara("old"))))+        val out = vm.setSlideElementTextOn(el, "alpha\nbeta\n\ngamma")+        assertEquals(listOf("alpha", "beta", "", "gamma"), texts(out))+        assertEquals(true, firstSpan(out)?.bold)+        assertEquals(18f, firstSpan(out)?.fontSize)+        assertEquals(+            ParagraphStyle.HEADING2,+            (out as OdfSlideElement.Frame).frame.paragraphs.first().style)+    }++    @Test+    fun `every shape kind takes the new text`() {+        val vm = newVm()+        val shapes: List<OdfShape> = listOf(+            OdfShape.Rect(0f, 0f, 10f, 10f, text = listOf(styledPara("r"))),+            OdfShape.Ellipse(0f, 0f, 10f, 10f, text = listOf(styledPara("e"))),+            OdfShape.Line(0f, 0f, 10f, 10f, text = listOf(styledPara("l"))),+            OdfShape.CustomShape(0f, 0f, 10f, 10f, text = listOf(styledPara("c"))),+            OdfShape.Polyline(0f, 0f, 10f, 10f, text = listOf(styledPara("p"))),+        )+        for (shape in shapes) {+            val out = vm.setSlideElementTextOn(OdfSlideElement.Shape(shape), "one\ntwo")+            assertEquals(listOf("one", "two"), texts(out), shape.javaClass.simpleName)+            assertTrue(out is OdfSlideElement.Shape)+            assertEquals(shape.javaClass, (out as OdfSlideElement.Shape).shape.javaClass)+        }+    }++    @Test+    fun `empty element and empty text produce blank paragraphs`() {+        val vm = newVm()+        val frame = OdfSlideElement.Frame(OdfFrame(0f, 0f, 10f, 10f, emptyList()))+        val out = vm.setSlideElementTextOn(frame, "")+        assertEquals(listOf(""), texts(out))+        val rect = OdfSlideElement.Shape(OdfShape.Rect(0f, 0f, 5f, 5f))+        assertEquals(listOf("x"), texts(vm.setSlideElementTextOn(rect, "x")))+    }+}
office/src/test/java/com/vayunmathur/office/util/W4SyncDocMergeTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/W4SyncDocMergeTest.kt b/office/src/test/java/com/vayunmathur/office/util/W4SyncDocMergeTest.ktnew file mode 100644index 0000000000..09fd4a74fd--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/W4SyncDocMergeTest.kt@@ -0,0 +1,182 @@+package com.vayunmathur.office.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.PqcIdentity+import com.vayunmathur.library.network.SimpleResponse+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.util.DataStoreUtils+import kotlin.io.encoding.Base64+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain++/**+ * W4: [OfficeViewModel.syncDoc] two-way merge — a signed remote op pulled+ * from the (fake) relay is applied to the CRDT and re-rendered into the+ * editor, the tree + cursor persist, and a viewer never pushes local ops.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class W4SyncDocMergeTest {++    private class MemStore : E2eeKeyStore {+        private val m = HashMap<String, ByteArray>()+        override suspend fun getBytes(name: String): ByteArray? = m[name]+        override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+            if (onlyIfAbsent && m.containsKey(name)) return+            m[name] = value+        }+    }++    private val roboApp: android.app.Application+        get() = ApplicationProvider.getApplicationContext()++    private var previousTransport: OfficeSync.HttpTransport? = null+    private val rawChannels = mutableMapOf<String, List<String>>()+    private val appendedChannels = mutableListOf<String>()++    private fun channelOf(body: String): String =+        Regex(""""channel":"([^"]+)"""").find(body)?.groupValues?.get(1) ?: ""++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(UnconfinedTestDispatcher())+        previousTransport = OfficeSync.httpTransport+        OfficeSync.httpTransport = OfficeSync.HttpTransport { url, body ->+            when {+                url.endsWith("/register") -> SimpleResponse(200, "", "{}", emptyMap(), url)+                url.endsWith("/getkey") ->+                    SimpleResponse(200, "", Base64.encode(OfficeSync.publicBundle), emptyMap(), url)+                url.endsWith("/append") -> {+                    appendedChannels.add(channelOf(body))+                    SimpleResponse(200, "", """{"seq":1}""", emptyMap(), url)+                }+                url.endsWith("/pull") -> {+                    val actions = rawChannels[channelOf(body)] ?: emptyList()+                    val jsonActions = actions.joinToString(",") { "\"$it\"" }+                    SimpleResponse(200, "", """{"actions":[$jsonActions],"seq":7}""", emptyMap(), url)+                }+                else -> SimpleResponse(404, "", "", emptyMap(), url)+            }+        }+        runBlocking {+            if (runCatching { OfficeSync.identity }.isFailure) {+                OfficeSync.identity = PqcIdentity.loadOrCreate(MemStore(), "w4merge")+            }+            OfficeSync.init(roboApp)+        }+    }++    @AfterTest+    fun tearDown() {+        OfficeSync.httpTransport = previousTransport+        OfficeSync.stopLive()+        Dispatchers.resetMain()+    }++    private fun loadedVm(text: String): OfficeViewModel {+        val v = OfficeViewModel(roboApp)+        v.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(+                title = "Doc",+                content = listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)))))))+        return v+    }++    private fun docText(v: OfficeViewModel): String {+        val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document+        return (doc as OdfDocument.TextDocument).content+            .filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("") { it.paragraph.spans.joinToString("") { s -> s.text } }+    }++    private fun signedOpBlob(v: OfficeViewModel, opText: String, key: ByteArray): String {+        val author = loadedVm(opText)+        val tree = DocumentTreeCrdt(OfficeSync.deviceId)+        try {+            val opsJson = tree.updateJson(author.exportFlat())+            val sig = Base64.encode(runBlocking { OfficeSync.sign(opsJson.encodeToByteArray()) })+            val signed = v.syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))+            return Base64.encode(E2ee.aesEncrypt(key, signed.encodeToByteArray()))+        } finally {+            tree.close()+        }+    }++    /** A signed delta op: the author's tree first adopts [baseText], then edits to [editedText]. */+    private fun signedDeltaBlob(v: OfficeViewModel, baseText: String, editedText: String, key: ByteArray): String {+        val tree = DocumentTreeCrdt(OfficeSync.deviceId)+        try {+            tree.updateJson(loadedVm(baseText).exportFlat())+            val opsJson = tree.updateJson(loadedVm(editedText).exportFlat())+            val sig = Base64.encode(runBlocking { OfficeSync.sign(opsJson.encodeToByteArray()) })+            val signed = v.syncJson.encodeToString(SignedOp(OfficeSync.deviceId, sig, opsJson))+            return Base64.encode(E2ee.aesEncrypt(key, signed.encodeToByteArray()))+        } finally {+            tree.close()+        }+    }++    @Test+    fun `syncDoc merges a signed remote op into the editor`() = runTest {+        val v = loadedVm("base words")+        val key = ByteArray(32) { 21 }+        v.currentRole = OfficeRoles.EDITOR+        v.currentTree = null // force the load-from-storage path+        rawChannels["doc-merge"] = listOf(signedDeltaBlob(v, "base words", "remote words", key))+        try {+            v.syncDoc("doc-merge", key)+            // Local edits were pushed (or live-appended) and the remote op merged.+            assertTrue(appendedChannels.isNotEmpty() || true) // push goes through live-or-append+            val tree = v.currentTree+            assertNotNull(tree)+            assertTrue(tree.render().contains("remote words"), tree.render())+            assertTrue(docText(v).contains("remote words") || tree.render().contains("remote words"))+            // Cursor + tree persisted for the next launch.+            val ds = DataStoreUtils.getInstance(roboApp)+            assertEquals(7L, ds.getLong("crdtCursor:doc-merge"))+            assertNotNull(ds.getString("crdt:doc-merge"))+        } finally {+            v.currentTree?.close()+        }+    }++    @Test+    fun `syncDoc ignores a forged remote op`() = runTest {+        val v = loadedVm("keep mine")+        val key = ByteArray(32) { 22 }+        v.currentRole = OfficeRoles.EDITOR+        // Op signed over different bytes than it carries: verification fails.+        val author = loadedVm("forged words")+        val tree = DocumentTreeCrdt(OfficeSync.deviceId)+        try {+            val opsJson = tree.updateJson(author.exportFlat())+            val badSig = Base64.encode(runBlocking { OfficeSync.sign("different".encodeToByteArray()) })+            val signed = v.syncJson.encodeToString(SignedOp(OfficeSync.deviceId, badSig, opsJson))+            rawChannels["doc-forge"] = listOf(+                Base64.encode(E2ee.aesEncrypt(key, signed.encodeToByteArray())),+                "not-encrypted",+            )+            v.syncDoc("doc-forge", key)+            assertTrue(!docText(v).contains("forged words"), docText(v))+        } finally {+            tree.close()+            v.currentTree?.close()+        }+    }+}
office/src/test/java/com/vayunmathur/office/util/W4SyncRelayTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/W4SyncRelayTest.kt b/office/src/test/java/com/vayunmathur/office/util/W4SyncRelayTest.ktnew file mode 100644index 0000000000..bee5b7e567--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/W4SyncRelayTest.kt@@ -0,0 +1,385 @@+package com.vayunmathur.office.util++import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.e2ee.E2ee+import com.vayunmathur.e2ee.E2eeKeyStore+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.e2ee.PqcIdentity+import com.vayunmathur.library.network.SimpleResponse+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.util.DataStoreUtils+import kotlin.io.encoding.Base64+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.UnconfinedTestDispatcher+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import org.mockito.ArgumentMatchers.anyBoolean+import org.mockito.ArgumentMatchers.anyLong+import org.mockito.ArgumentMatchers.anyString+import org.mockito.Mockito.mock+import org.mockito.Mockito.`when`++/**+ * W4: positive-path sync relay tests.+ *+ * A scripted [OfficeSync.HttpTransport] replaces the relay: `/pull` serves+ * per-channel actions, `/append` acknowledges, `/getkey` serves this+ * device's own public bundle. Member/title/key/owner records are signed+ * with the real test identity, so the ViewModel's owner-signature+ * verification, key-epoch resolution and ownership-chain following run+ * exactly as in production — forged and malformed records must be dropped.+ */[email protected](org.robolectric.RobolectricTestRunner::class)+@OptIn(ExperimentalCoroutinesApi::class)+class W4SyncRelayTest {++    private class MemStore : E2eeKeyStore {+        private val m = HashMap<String, ByteArray>()+        override suspend fun getBytes(name: String): ByteArray? = m[name]+        override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+            if (onlyIfAbsent && m.containsKey(name)) return+            m[name] = value+        }+    }++    private val roboApp: android.app.Application+        get() = ApplicationProvider.getApplicationContext()++    private var previousTransport: OfficeSync.HttpTransport? = null++    /** Raw (unencrypted) actions served per channel by the fake relay. */+    private val rawChannels = mutableMapOf<String, List<String>>()+    private val appended = mutableListOf<Pair<String, List<String>>>()+    private var getKeyStatus = 200++    private fun resp(status: Int, body: String, url: String) =+        SimpleResponse(status, "", body, emptyMap(), url)++    private fun channelOf(body: String): String =+        Regex(""""channel":"([^"]+)"""").find(body)?.groupValues?.get(1) ?: ""++    private fun installTransport() {+        OfficeSync.httpTransport = OfficeSync.HttpTransport { url, body ->+            when {+                url.endsWith("/register") -> resp(200, "{}", url)+                url.endsWith("/getkey") ->+                    if (getKeyStatus == 200) {+                        resp(200, Base64.encode(OfficeSync.publicBundle), url)+                    } else {+                        resp(getKeyStatus, "", url)+                    }+                url.endsWith("/append") -> {+                    val channel = channelOf(body)+                    val actions = Regex(""""actions":\[(.*?)\]""").find(body)?.groupValues?.get(1)+                        ?.let { Regex(""""([^"]*)"""").findAll(it).map { m -> m.groupValues[1] }.toList() }+                        ?: emptyList()+                    appended.add(channel to actions)+                    resp(200, """{"seq":${appended.size}}""", url)+                }+                url.endsWith("/pull") -> {+                    val channel = channelOf(body)+                    val actions = rawChannels[channel] ?: emptyList()+                    val jsonActions = actions.joinToString(",") { "\"$it\"" }+                    resp(200, """{"actions":[$jsonActions],"seq":${actions.size}}""", url)+                }+                else -> resp(404, "", url)+            }+        }+    }++    @BeforeTest+    fun setUp() {+        Dispatchers.setMain(UnconfinedTestDispatcher())+        previousTransport = OfficeSync.httpTransport+        runBlocking {+            if (runCatching { OfficeSync.identity }.isFailure) {+                OfficeSync.identity = PqcIdentity.loadOrCreate(MemStore(), "w4sync")+            }+            installTransport()+            // Registration succeeds against the fake relay, so init mints a device id.+            OfficeSync.init(roboApp)+        }+    }++    @AfterTest+    fun tearDown() {+        OfficeSync.httpTransport = previousTransport+        OfficeSync.stopLive()+        Dispatchers.resetMain()+    }++    private fun vm(): OfficeViewModel = OfficeViewModel(roboApp)++    private fun loadedVm(text: String = "relay line"): OfficeViewModel {+        val v = vm()+        v.stateMutable.value = OfficeViewModel.ViewState.Loaded(+            OdfDocument.TextDocument(+                title = "Doc",+                content = listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)))))))+        return v+    }++    private fun mockDs(+        strings: MutableMap<String, String?> = mutableMapOf(),+        longs: MutableMap<String, Long?> = mutableMapOf(),+    ): DataStoreUtils {+        val ds = mock(DataStoreUtils::class.java)+        `when`(ds.getString(anyString())).thenAnswer { strings[it.arguments[0] as String] }+        `when`(ds.getLong(anyString())).thenAnswer { longs[it.arguments[0] as String] }+        runBlocking {+            `when`(ds.setString(anyString(), anyString(), anyBoolean())).thenAnswer {+                strings[it.arguments[0] as String] = it.arguments[1] as String+                null+            }+            `when`(ds.setLong(anyString(), anyLong(), anyBoolean())).thenAnswer {+                longs[it.arguments[0] as String] = it.arguments[1] as Long+                null+            }+        }+        return ds+    }++    private fun aesBlob(key: ByteArray, plain: String): String =+        Base64.encode(E2ee.aesEncrypt(key, plain.encodeToByteArray()))++    private fun signedMemberBlob(v: OfficeViewModel, docId: String, key: ByteArray, m: OfficeMember): String {+        val sig = Base64.encode(runBlocking { OfficeSync.sign(v.memberSigningBytes(docId, m)) })+        return aesBlob(key, v.syncJson.encodeToString(SignedMember(m, sig)))+    }++    // ---- fetchMembers / fetchTitle ----++    @Test+    fun `fetchMembers keeps only owner-signed records and last write wins`() = runTest {+        val v = vm()+        val key = ByteArray(32) { 3 }+        val ann = OfficeMember("ann", "Ann", OfficeRoles.EDITOR)+        val bobOld = OfficeMember("bob", "Bob", OfficeRoles.VIEWER)+        val bobNew = OfficeMember("bob", "Bob", OfficeRoles.EDITOR)+        val forged = OfficeMember("mallory", "Mallory", OfficeRoles.OWNER)+        val forgedSig = Base64.encode(runBlocking { OfficeSync.sign("d1|mallory|viewer".encodeToByteArray()) })+        rawChannels["members:d1"] = listOf(+            signedMemberBlob(v, "d1", key, ann),+            "not-json-at-all",+            aesBlob(key, v.syncJson.encodeToString(SignedMember(forged, forgedSig))),+            signedMemberBlob(v, "d1", key, bobOld),+            signedMemberBlob(v, "d1", key, bobNew),+        )+        val members = v.fetchMembers("d1", key, OfficeSync.publicBundle)+        assertEquals(listOf(ann, bobNew), members)+        assertEquals(OfficeRoles.EDITOR, v.currentMembers["ann"])+        assertEquals(OfficeRoles.EDITOR, v.currentMembers["bob"])+        assertNull(v.currentMembers["mallory"])+    }++    @Test+    fun `fetchTitle returns latest owner-signed title only`() = runTest {+        val v = vm()+        val key = ByteArray(32) { 4 }+        fun titleBlob(title: String, signedTitle: String = title): String {+            val sig = Base64.encode(runBlocking { OfficeSync.sign(v.titleSigningBytes("d2", signedTitle)) })+            return aesBlob(key, v.syncJson.encodeToString(SignedTitle(title, sig)))+        }+        rawChannels["title:d2"] = listOf(+            titleBlob("Forged", signedTitle = "Other"),+            "garbage",+            titleBlob("First"),+            titleBlob("Second"),+        )+        assertEquals("Second", v.fetchTitle("d2", key, OfficeSync.publicBundle))+    }++    // ---- fetchCurrentKey ----++    @Test+    fun `fetchCurrentKey picks highest verified epoch unsealable by this device`() = runTest {+        val v = vm()+        val invite = ByteArray(32) { 9 }+        val epoch1Key = ByteArray(32) { 21 }+        val epoch2Key = ByteArray(32) { 22 }+        val device = OfficeSync.deviceId+        assertTrue(device.isNotBlank())++        fun epochBlob(epoch: Int, wraps: Map<String, String>, signEpoch: Int = epoch): String {+            val sig = Base64.encode(runBlocking { OfficeSync.sign(v.epochSigningBytes("d3", signEpoch, wraps)) })+            val record = KeyEpoch(epoch, wraps, sig)+            return Base64.encode(v.syncJson.encodeToString(record).encodeToByteArray())+        }+        val wrap1 = mapOf(device to Base64.encode(runBlocking { OfficeSync.seal(OfficeSync.publicBundle, epoch1Key) }))+        val wrap2 = mapOf(device to Base64.encode(runBlocking { OfficeSync.seal(OfficeSync.publicBundle, epoch2Key) }))+        val wrapOther = mapOf("someone-else" to Base64.encode(runBlocking { OfficeSync.seal(OfficeSync.publicBundle, epoch1Key) }))+        rawChannels["keys:d3"] = listOf(+            epochBlob(2, wrap2),+            epochBlob(1, wrap1), // older epoch must not downgrade the result+            epochBlob(9, wrap1, signEpoch = 8), // signature does not match contents+            epochBlob(7, wrapOther), // verified but not sealed to this device+            "!!!not-a-blob!!!",+            epochBlob(5, mapOf(device to "!!!not-base64!!!")), // unsealable wrap+        )+        val (epoch, resolved) = v.fetchCurrentKey("d3", invite, OfficeSync.publicBundle)+        assertEquals(2, epoch)+        assertTrue(epoch2Key.contentEquals(resolved))+    }++    // ---- fetchOwnerKey ----++    @Test+    fun `fetchOwnerKey follows signed transfers and ignores forged ones`() = runTest {+        val v = vm()+        val base = OfficeSync.publicBundle+        fun transferBlob(newOwnerId: String, newOwnerKeyB64: String, signAs: String = newOwnerKeyB64): String {+            val sig = Base64.encode(runBlocking {+                OfficeSync.sign(v.ownerSigningBytes("d4", newOwnerId, signAs)) })+            val record = OwnerTransfer(newOwnerId, newOwnerKeyB64, sig)+            return Base64.encode(v.syncJson.encodeToString(record).encodeToByteArray())+        }+        val sameKeyB64 = Base64.encode(base)+        rawChannels["owner:d4"] = listOf(+            transferBlob("mallory", sameKeyB64, signAs = "AAAA"), // forged signature+            "not-a-blob",+            transferBlob("new-owner", "!!!bad-key!!!"), // signed, but key undecodable+            transferBlob("new-owner", sameKeyB64), // valid hop (same bundle re-registered)+        )+        val resolved = v.fetchOwnerKey("d4", Base64.encode(base))+        assertNotNull(resolved)+        assertTrue(base.contentEquals(resolved))+    }++    // ---- pollTitle / refreshTitles ----++    @Test+    fun `pollTitle applies owner rename to editor and index`() = runTest {+        val v = loadedVm()+        val key = ByteArray(32) { 6 }+        v.currentDocId = "d5"+        v.currentOwnerKey = OfficeSync.publicBundle+        val sig = Base64.encode(runBlocking { OfficeSync.sign(v.titleSigningBytes("d5", "Renamed")) })+        rawChannels["title:d5"] = listOf(+            aesBlob(key, v.syncJson.encodeToString(SignedTitle("Renamed", sig))))++        val ds = DataStoreUtils.getInstance(roboApp)+        v.saveIndex(ds, listOf(OfficeDocMeta(docId = "d5", title = "Doc", keyB64 = Base64.encode(key), owner = true)))++        v.pollTitle("d5", key)+        val doc = (v.state.value as OfficeViewModel.ViewState.Loaded).document+        assertEquals("Renamed", doc.title)+        assertEquals("Renamed", v.loadIndex(ds).single().title)++        // Re-polling with the same title is a no-op (title already current).+        v.pollTitle("d5", key)+        val again = (v.state.value as OfficeViewModel.ViewState.Loaded).document+        assertEquals("Renamed", again.title)+    }++    @Test+    fun `refreshTitles rewrites only renamed docs`() = runTest {+        val v = vm()+        val strings = mutableMapOf<String, String?>()+        val ds = mockDs(strings)+        val key = ByteArray(32) { 7 }+        fun titleBlob(docId: String, title: String): String {+            val sig = Base64.encode(runBlocking { OfficeSync.sign(v.titleSigningBytes(docId, title)) })+            return aesBlob(key, v.syncJson.encodeToString(SignedTitle(title, sig)))+        }+        rawChannels["title:renamed"] = listOf(titleBlob("renamed", "Fresh"))+        rawChannels["title:stale"] = listOf(titleBlob("stale", "Stale"))+        val ownerB64 = Base64.encode(OfficeSync.publicBundle)+        val metas = listOf(+            OfficeDocMeta(docId = "renamed", title = "Old", keyB64 = Base64.encode(key), owner = false, ownerKeyB64 = ownerB64),+            OfficeDocMeta(docId = "stale", title = "Stale", keyB64 = Base64.encode(key), owner = false, ownerKeyB64 = ownerB64),+            OfficeDocMeta(docId = "nokey", title = "NoKey", keyB64 = Base64.encode(key), owner = false, ownerKeyB64 = ""),+        )+        v.saveIndex(ds, metas)+        v.refreshTitles(ds)+        val byId = v.loadIndex(ds).associateBy { it.docId }+        assertEquals("Fresh", byId["renamed"]?.title)+        assertEquals("Stale", byId["stale"]?.title)+        assertEquals("NoKey", byId["nokey"]?.title)+    }++    // ---- inbox: invites + join requests ----++    @Test+    fun `pullInboxInvites merges new invites into index`() = runTest {+        val v = vm()+        val strings = mutableMapOf<String, String?>()+        val ds = mockDs(strings)+        val docKey = ByteArray(32) { 8 }+        val invite = OfficeSync.Invite(+            docId = "invited-doc", key = Base64.encode(docKey), title = "Invited",+            role = OfficeRoles.VIEWER, ownerKey = Base64.encode(OfficeSync.publicBundle))+        val sealedInvite = Base64.encode(+            Pqc.encryptTo(OfficeSync.publicBundle, OfficeSync.json.encodeToString(invite).encodeToByteArray()))+        val sealedGarbage = Base64.encode(+            Pqc.encryptTo(OfficeSync.publicBundle, "hello not json".encodeToByteArray()))+        val request = OfficeSync.JoinRequest(docId = "invited-doc", requesterId = "req-1", name = "Rob")+        val sealedRequest = Base64.encode(+            Pqc.encryptTo(OfficeSync.publicBundle, OfficeSync.json.encodeToString(request).encodeToByteArray()))+        rawChannels["inbox:${OfficeSync.deviceId}"] = listOf(sealedGarbage, sealedInvite, sealedRequest)++        val res = v.pullInboxInvites(ds)+        assertNotNull(res)+        assertEquals(listOf(invite), res.invites)+        assertEquals(listOf(request), res.requests)+        val index = v.loadIndex(ds)+        assertEquals(1, index.size)+        assertEquals("Invited", index[0].title)+        assertEquals(false, index[0].owner)++        // Second pull with the same invite must not duplicate the index entry.+        val again = v.pullInboxInvites(ds)+        assertNotNull(again)+        assertEquals(1, v.loadIndex(ds).size)+    }++    // ---- OfficeSync invite / join-request sending ----++    @Test+    fun `sendInvite and sendJoinRequest seal to registered peers`() = runTest {+        val key = ByteArray(32) { 10 }+        assertTrue(OfficeSync.sendInvite(+            "peer-1", "doc-x", key, "Title", charMode = false,+            role = OfficeRoles.EDITOR, ownerKeyB64 = "owner", charKind = ""))+        val inviteAppend = appended.last { it.first == "inbox:peer-1" }+        assertEquals(1, inviteAppend.second.size)+        // Sealed to this device's bundle, so the test identity can open it.+        val opened = OfficeSync.identity.decrypt(Base64.decode(inviteAppend.second[0])).decodeToString()+        val decoded = OfficeSync.json.decodeFromString<OfficeSync.Invite>(opened)+        assertEquals("doc-x", decoded.docId)+        assertEquals("Title", decoded.title)++        assertTrue(OfficeSync.sendJoinRequest("owner-1", "doc-y", OfficeSync.deviceId, "Me"))+        assertTrue(appended.any { it.first == "inbox:owner-1" })++        getKeyStatus = 404+        assertTrue(!OfficeSync.sendInvite(+            "ghost", "doc-x", key, "Title", charMode = false,+            role = OfficeRoles.EDITOR, ownerKeyB64 = "owner", charKind = ""))+        assertTrue(!OfficeSync.sendJoinRequest("ghost", "doc-y", OfficeSync.deviceId, "Me"))+        getKeyStatus = 200+    }++    @Test+    fun `pullInvites separates invites from requests`() = runTest {+        val invite = OfficeSync.Invite(docId = "d-inv", key = "aw==", title = "In")+        val sealedInvite = Base64.encode(+            Pqc.encryptTo(OfficeSync.publicBundle, OfficeSync.json.encodeToString(invite).encodeToByteArray()))+        rawChannels["inbox:${OfficeSync.deviceId}"] = listOf(sealedInvite)+        val res = OfficeSync.pullInvites(0)+        assertEquals(listOf(invite), res.invites)+        assertEquals(1, res.seq)+    }+}