office: add tests for ooxml slice 1/4 (docx/pptx/xlsx import/export)
- Commit
651c3e9681ff5de09f323dbb21feba23b0f33f75- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 18:24 UTC (29 days ago)
- Parents
5a04948
Slice coverage 92.9% INSTRUCTION over Ooxml* classes (merged report). Covers: run/para formatting, style inheritance incl. chained-overlay regression, numbering, sections, fields, hyperlinks, notes/comments, headers/footers, tables, drawings/images/charts/textbox/smartart, xlsx styles/formats/dates/validations/condformats/comments/tables/drawings, pptx shapes/groups/placeholders/text/transitions/notes, package/rels/ content-types, importer dispatch incl. encrypted guards, theme/color/units helpers, chart model. (cherry picked from commit b57152117ffe3fcb9d5ee6c706b0833ca6846438)
Diff
office/src/test/java/com/vayunmathur/office/odf/OoxmlChartSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlChartSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlChartSliceTest.ktnew file mode 100644index 0000000000..2d91a652f9--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlChartSliceTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.ChartType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): tests for [OoxmlChart] — chart type mapping, series/categories parsing,+ * titles/legend/axes, per-series colors and data labels, stacked promotion, sparse idx alignment.+ */+class OoxmlChartSliceTest {++ private fun chart(+ typeTag: String = "<barChart><barDir val=\"col\"/><grouping val=\"clustered\"/>",+ typeClose: String = "</barChart>",+ body: String = SERIES1,+ extra: String = ""+ ) = "<chartSpace xmlns:c=\"c\" xmlns:a=\"a\"><chart><plotArea>$typeTag$body$typeClose</plotArea>$extra</chart></chartSpace>"++ companion object {+ private const val SERIES1 =+ "<ser><tx><v>S1</v></tx>" ++ "<cat><strRef><strCache><pt idx=\"0\"><v>A</v></pt><pt idx=\"1\"><v>B</v></pt></strCache></strRef></cat>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>10</v></pt><pt idx=\"1\"><v>20</v></pt></numCache></numRef></val>" ++ "</ser>"+ }++ @Test fun barChartBasics() {+ val c = OoxmlChart.parse(chart())!!+ assertEquals(ChartType.BAR, c.type)+ assertEquals(listOf("A", "B"), c.categories)+ assertEquals(1, c.series.size)+ assertEquals("S1", c.series[0].name)+ assertEquals(listOf(10f, 20f), c.series[0].values)+ assertFalse(c.legend)+ assertFalse(c.stacked)+ }++ @Test fun chartTypeMapping() {+ val cases = mapOf(+ "barChart" to ChartType.BAR, "bar3DChart" to ChartType.BAR,+ "lineChart" to ChartType.LINE, "line3DChart" to ChartType.LINE,+ "pieChart" to ChartType.PIE, "pie3DChart" to ChartType.PIE, "ofPieChart" to ChartType.PIE,+ "doughnutChart" to ChartType.DONUT,+ "areaChart" to ChartType.AREA, "area3DChart" to ChartType.AREA,+ "scatterChart" to ChartType.SCATTER,+ "radarChart" to ChartType.RADAR,+ "bubbleChart" to ChartType.BUBBLE)+ for ((tag, expected) in cases) {+ val open = if (tag == "scatterChart" || tag == "bubbleChart") "<$tag>" else "<$tag>"+ val c = OoxmlChart.parse(chart(open, "</$tag>"))!!+ assertEquals(expected, c.type, "tag $tag")+ }+ }++ @Test fun scatterUsesXYVals() {+ val body = "<ser><tx><v>pts</v></tx>" ++ "<xVal><numRef><numCache><pt idx=\"0\"><v>1</v></pt></numCache></numRef></xVal>" ++ "<yVal><numRef><numCache><pt idx=\"0\"><v>5</v></pt><pt idx=\"1\"><v>6</v></pt></numCache></numRef></yVal></ser>"+ val c = OoxmlChart.parse(chart("<scatterChart>", "</scatterChart>", body))!!+ assertEquals(ChartType.SCATTER, c.type)+ assertEquals(listOf(5f, 6f), c.series[0].values)+ assertEquals(listOf("1", ""), c.categories)+ }++ @Test fun emptyChartIsNull() {+ assertNull(OoxmlChart.parse("<chartSpace><chart><plotArea><barChart/></plotArea></chart></chartSpace>"))+ // Series with no numeric values is not plottable.+ val noVals = "<ser><tx><v>S</v></tx><cat><strRef><strCache><pt idx=\"0\"><v>A</v></pt></strCache></strRef></cat></ser>"+ assertNull(OoxmlChart.parse(chart(body = noVals)))+ }++ @Test fun stackedBarPromotesType() {+ val c = OoxmlChart.parse(+ chart("<barChart><barDir val=\"col\"/><grouping val=\"stacked\"/>"))!!+ assertEquals(ChartType.STACKED_BAR, c.type)+ assertTrue(c.stacked)+ val pct = OoxmlChart.parse(+ chart("<barChart><barDir val=\"bar\"/><grouping val=\"percentStacked\"/>"))!!+ assertEquals(ChartType.STACKED_BAR, pct.type)+ }++ @Test fun titleLegendAndAxes() {+ val extra = "<title><tx><rich><p><r><t>My Title</t></r></p></rich></tx></title>" ++ "<legend><legendPos val=\"r\"/></legend>" ++ "<catAx><title><tx><rich><p><r><t>Months</t></r></p></rich></tx></title></catAx>" ++ "<valAx><title><tx><rich><p><r><t>Sales</t></r></p></rich></tx></title></valAx>"+ val c = OoxmlChart.parse(chart(extra = extra))!!+ assertEquals("My Title", c.title)+ assertTrue(c.legend)+ assertEquals("Months", c.xAxisTitle)+ assertEquals("Sales", c.yAxisTitle)+ }++ @Test fun barDirSwapsAxes() {+ val extra = "<catAx><title><tx><rich><p><r><t>C</t></r></p></rich></tx></title></catAx>" ++ "<valAx><title><tx><rich><p><r><t>V</t></r></p></rich></tx></title></valAx>"+ val c = OoxmlChart.parse(chart("<barChart><barDir val=\"bar\"/>", extra = extra))!!+ assertEquals("V", c.xAxisTitle)+ assertEquals("C", c.yAxisTitle)+ }++ @Test fun seriesColorAndDataLabels() {+ val body = "<ser><tx><v>S</v></tx>" ++ "<spPr><solidFill><srgbClr val=\"FF0000\"/></solidFill></spPr>" ++ "<dLbls><showVal val=\"1\"/></dLbls>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>3</v></pt></numCache></numRef></val></ser>"+ val c = OoxmlChart.parse(chart(body = body))!!+ assertEquals(0xFFFF0000L, c.series[0].color)+ assertTrue(c.series[0].dataLabels)+ }++ @Test fun firstChartTypeWins() {+ val xml = "<chartSpace><chart><plotArea><barChart>$SERIES1</barChart>" ++ "<lineChart>$SERIES1</lineChart></plotArea></chart></chartSpace>"+ assertEquals(ChartType.BAR, OoxmlChart.parse(xml)!!.type)+ }++ @Test fun missingSeriesNameDefaults() {+ val body = "<ser><val><numRef><numCache><pt idx=\"0\"><v>1</v></pt></numCache></numRef></val></ser>"+ val c = OoxmlChart.parse(chart(body = body))!!+ assertEquals("Series 1", c.series[0].name)+ }++ @Test fun sparseIdxStaysAligned() {+ val two = "<ser><tx><v>two</v></tx>" ++ "<cat><strRef><strCache><pt idx=\"0\"><v>a</v></pt><pt idx=\"2\"><v>c</v></pt></strCache></strRef></cat>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>1</v></pt><pt idx=\"2\"><v>3</v></pt></numCache></numRef></val></ser>"+ val c = OoxmlChart.parse(chart(body = two))!!+ assertEquals(listOf("a", "", "c"), c.categories)+ assertEquals(listOf(1f, 0f, 3f), c.series[0].values)+ }++ @Test fun nonNumericValueIgnored() {+ val body = "<ser><tx><v>S</v></tx>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>abc</v></pt><pt idx=\"1\"><v>2</v></pt></numCache></numRef></val></ser>"+ val c = OoxmlChart.parse(chart(body = body))!!+ assertEquals(listOf(0f, 2f), c.series[0].values)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlDirectSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlDirectSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlDirectSliceTest.ktnew file mode 100644index 0000000000..1868069f3b--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlDirectSliceTest.kt@@ -0,0 +1,243 @@+package com.vayunmathur.office.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): direct importer entry-point tests. These call [OoxmlDocx], [OoxmlXlsx] and+ * [OoxmlPptx] directly (bypassing [OoxmlImporter]'s best-effort fallback) so failures surface+ * the real exception, plus direct unit tests for style-table resolution and run-prop overlays.+ */+class OoxmlDirectSliceTest {++ private fun zipBytes(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()+ }++ private fun pkgBytes(pkg: OoxmlPackage): ByteArray {+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ for ((n, c) in pkg.entries) {+ zos.putNextEntry(java.util.zip.ZipEntry(n))+ zos.write(c.toByteArray(Charsets.UTF_8))+ zos.closeEntry()+ }+ }+ return bos.toByteArray()+ }++ @Test fun stylesParseCharStyleColor() {+ val styles = OoxmlDocxStyles.parseStyles(+ "<w:styles xmlns:w=\"w\">" ++ "<w:style w:styleId=\"Em\" w:type=\"character\">" ++ "<w:rPr><w:i/><w:color w:val=\"FF0000\"/></w:rPr></w:style></w:styles>",+ OoxmlTheme.DEFAULT)+ val def = styles.byId["Em"]+ assertNotNull(def, "Em style missing from ${styles.byId.keys}")+ assertTrue(def.rpr.italic == true, "italic was ${def.rpr.italic}")+ assertNotNull(def.rpr.color, "parsed color is null")+ assertEquals(0xFFFF0000L, def.rpr.color)+ }++ @Test fun charStyleOverlayKeepsColor() {+ val styles = OoxmlDocxStyles.parseStyles(+ "<w:styles xmlns:w=\"w\">" ++ "<w:style w:styleId=\"Em\" w:type=\"character\">" ++ "<w:rPr><w:i/><w:color w:val=\"FF0000\"/></w:rPr></w:style></w:styles>",+ OoxmlTheme.DEFAULT)+ val eff = styles.charStyleRPr("Em")+ assertEquals(0xFFFF0000L, eff.color)+ assertTrue(eff.italic == true)+ }++ @Test fun rprOverlayMergesAllFields() {+ val base = OoxmlDocxStyles.RPr(bold = true, sizeHalfPt = 20, color = 0xFF000000L)+ val over = OoxmlDocxStyles.RPr(italic = true, color = 0xFFFF0000L)+ val merged = base.overlay(over)+ assertTrue(merged.bold == true)+ assertTrue(merged.italic == true)+ assertEquals(20, merged.sizeHalfPt)+ assertEquals(0xFFFF0000L, merged.color)+ }++ @Test fun rprOverlayChainKeepsEarlierDecor() {+ // Chained overlays must not wipe decor props when a later layer leaves them null+ // (regression: split overlayText/overlayDecor passes dropped them).+ val charStyle = OoxmlDocxStyles.RPr(italic = true, color = 0xFFFF0000L)+ val direct = OoxmlDocxStyles.RPr(styleId = "Em")+ val eff = OoxmlDocxStyles.RPr().overlay(charStyle).overlay(direct)+ assertTrue(eff.italic == true)+ assertEquals(0xFFFF0000L, eff.color)+ assertEquals("Em", eff.styleId)+ }++ @Test fun docxDirectCharStyle() {+ val stylesXml = "<w:styles xmlns:w=\"w\">" ++ "<w:style w:styleId=\"Em\" w:type=\"character\">" ++ "<w:rPr><w:i/><w:color w:val=\"FF0000\"/></w:rPr></w:style></w:styles>"+ val pkg = OoxmlPackage.read(zipBytes(+ "word/document.xml" to "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body>" ++ "<w:p><w:r><w:rPr><w:rStyle w:val=\"Em\"/></w:rPr><w:t>e</w:t></w:r></w:p>" ++ "</w:body></w:document>",+ "word/styles.xml" to stylesXml))+ // Isolate: does the retained styles.xml bytes parse to a red style?+ val reread = OoxmlDocxStyles.parseStyles(pkg.entries["word/styles.xml"]!!, OoxmlTheme.DEFAULT)+ assertEquals(0xFFFF0000L, reread.byId["Em"]?.rpr?.color, "reread styles entry lost color")+ val doc = OoxmlImporter.import(pkgBytes(pkg), "t.docx") as com.vayunmathur.library.ui.odf.OdfDocument.TextDocument+ val span = doc.content+ .filterIsInstance<com.vayunmathur.library.ui.odf.OdfContentBlock.Paragraph>()[0]+ .paragraph.spans[0]+ assertTrue(span.italic)+ assertEquals(0xFFFF0000L, span.color)+ }++ @Test fun xlsxDirectChartDrawing() {+ val pkg = OoxmlPackage.read(zipBytes(+ "xl/workbook.xml" to "<workbook xmlns=\"s\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><sheets><sheet name=\"S\" 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/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\"><v>1</v></c></row></sheetData>" ++ "<drawing r:id=\"d1\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" ++ "</worksheet>"),+ "xl/worksheets/_rels/sheet1.xml.rels" to ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"d1\" Type=\"http://t/drawing\" Target=\"../drawings/d1.xml\"/></Relationships>"),+ "xl/drawings/d1.xml" to ("<wsDr xmlns=\"d\"><oneCellAnchor>" ++ "<from><col>0</col><row>0</row><colOff>0</colOff><rowOff>0</rowOff></from>" ++ "<ext cx=\"914400\" cy=\"914400\"/>" ++ "<graphicFrame><graphic><graphicData><chart r:id=\"c1\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/></graphicData></graphic></graphicFrame>" ++ "</oneCellAnchor></wsDr>"),+ "xl/drawings/_rels/d1.xml.rels" to ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"c1\" Type=\"http://t/chart\" Target=\"../charts/c1.xml\"/></Relationships>"),+ "xl/charts/c1.xml" to ("<chartSpace><chart><plotArea><barChart>" ++ "<ser><tx><v>S</v></tx>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>4</v></pt></numCache></numRef></val></ser>" ++ "</barChart></plotArea></chart></chartSpace>")))+ val doc = OoxmlImporter.import(pkgBytes(pkg), "c.xlsx") as com.vayunmathur.library.ui.odf.OdfDocument.Spreadsheet+ assertEquals(1, doc.sheets[0].floating.size)+ }++ private fun txParas(+ xml: String,+ rels: Map<String, OoxmlPackage.Rel> = emptyMap()+ ): List<com.vayunmathur.library.ui.odf.OdfParagraph> {+ val parser = OoxmlXml.newParser(xml)+ var e = parser.eventType+ while (!(e == org.xmlpull.v1.XmlPullParser.START_TAG && parser.name == "txBody")) e = parser.next()+ val out = mutableListOf<com.vayunmathur.library.ui.odf.OdfParagraph>()+ val pkg = OoxmlPackage(emptyMap(), emptyMap())+ OoxmlPptxText.parseTxBody(+ parser,+ OoxmlPptx.SlideCtx(pkg, "part", OoxmlTheme.DEFAULT, rels),+ out)+ return out+ }++ @Test fun pptxDirectBullets() {+ val paras = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\"><a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:pPr lvl=\"0\"><a:buChar char=\"-\"/></a:pPr>" ++ "<a:r><a:t>bullet</a:t></a:r></a:p></p:txBody>")+ assertEquals(1, paras.size)+ assertEquals(com.vayunmathur.library.ui.odf.ListType.BULLET, paras[0].listType)+ assertEquals("-", paras[0].listBulletChar)+ assertEquals("bullet", paras[0].spans[0].text)+ }++ @Test fun pptxDirectNumberedAndPlain() {+ val paras = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\"><a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:pPr lvl=\"1\"><a:buAutoNum type=\"alphaLcPeriod\"/></a:pPr>" ++ "<a:r><a:t>one</a:t></a:r></a:p>" ++ "<a:p><a:pPr lvl=\"1\"><a:buAutoNum type=\"romanUcPeriod\"/></a:pPr>" ++ "<a:r><a:t>two</a:t></a:r></a:p>" ++ "<a:p><a:pPr><a:buNone/></a:pPr><a:r><a:t>plain</a:t></a:r></a:p></p:txBody>")+ assertEquals(3, paras.size)+ assertEquals(com.vayunmathur.library.ui.odf.ListType.NUMBERED, paras[0].listType)+ assertEquals("a", paras[0].listNumberFormat)+ assertEquals(1, paras[0].listItemIndex)+ assertEquals(2, paras[1].listItemIndex)+ assertEquals("I", paras[1].listNumberFormat)+ assertEquals(com.vayunmathur.library.ui.odf.ParagraphStyle.BODY, paras[2].style)+ }++ @Test fun pptxDirectEmptyPara() {+ val paras = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\"><a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:r><a:t></a:t></a:r></a:p>" ++ "<a:p><a:r><a:t>real</a:t></a:r></a:p></p:txBody>")+ assertEquals(1, paras.size)+ assertEquals("real", paras[0].spans[0].text)+ }++ @Test fun pptxDirectRunHyperlink() {+ val paras = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:r><a:rPr>" ++ "<a:hlinkClick r:id=\"h1\"/>" ++ "</a:rPr><a:t>linked</a:t></a:r></a:p></p:txBody>",+ mapOf("h1" to OoxmlPackage.Rel("h1", "https://r.test", "http://t/hyperlink", true)))+ assertEquals("https://r.test", paras[0].spans[0].href)+ }++ @Test fun pptxDirectRichRun() {+ val paras = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:r><a:rPr b=\"1\" i=\"1\" sz=\"1200\">" ++ "<a:solidFill><a:srgbClr val=\"00FF00\"/></a:solidFill>" ++ "<a:latin typeface=\"Verdana\"/>" ++ "<a:hlinkClick r:id=\"h1\"/>" ++ "</a:rPr><a:t>rich</a:t></a:r>" ++ "<a:br/><a:fld><a:rPr/><a:t>fld</a:t></a:fld></a:p></p:txBody>")+ val spans = paras[0].spans+ val rich = spans.first { it.text == "rich" }+ assertTrue(rich.bold && rich.italic)+ assertEquals(0xFF00FF00L, rich.color)+ assertEquals("Verdana", rich.fontFamily)+ assertEquals(12f, rich.fontSize!!, 0.01f)+ assertTrue(spans.any { it.text == "\n" })+ assertTrue(spans.any { it.text == "fld" })+ }++ @Test fun pptxDirectCapsRun() {+ // cap="all"/"small" maps to uppercase textTransform (covers the reader branch the+ // exporter round-trip cannot reach, since pptxRun() never writes cap).+ for (cap in listOf("all", "small")) {+ val paras = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\"><a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:r><a:rPr cap=\"$cap\"/><a:t>capped</a:t></a:r></a:p></p:txBody>")+ assertEquals("uppercase", paras[0].spans.first { it.text == "capped" }.textTransform, "cap=$cap")+ }+ val plain = txParas(+ "<p:txBody xmlns:p=\"p\" xmlns:a=\"a\"><a:bodyPr wrap=\"square\"/><a:lstStyle/>" ++ "<a:p><a:r><a:rPr/><a:t>plain</a:t></a:r></a:p></p:txBody>")+ assertEquals(null, plain[0].spans.first { it.text == "plain" }.textTransform)+ }++ @Test fun notesSlideRoundTrip() {+ // Notes slides are emitted by the exporter and parsed back by OoxmlPptx.parseNotes.+ val doc = com.vayunmathur.library.ui.odf.OdfDocument.Presentation(+ title = "n",+ slides = listOf(com.vayunmathur.library.ui.odf.OdfSlide(+ name = "S1",+ notes = listOf(com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan("remember this")))))))+ val back = OoxmlImporter.import(+ com.vayunmathur.library.ui.odf.OoxmlExporter.export(doc), "n.pptx")+ as com.vayunmathur.library.ui.odf.OdfDocument.Presentation+ assertTrue(back.slides[0].notes.any { it.spans.any { s -> s.text == "remember this" } })+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlDocxSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlDocxSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlDocxSliceTest.ktnew file mode 100644index 0000000000..6c81a70dd8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlDocxSliceTest.kt@@ -0,0 +1,586 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.ListType+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): docx importer tests ([OoxmlDocx] + [OoxmlDocxStyles]) — run/paragraph+ * formatting, style inheritance, numbering, sections, fields, hyperlinks, notes, headers/footers,+ * bookmarks, tracked changes, symbols and text boxes.+ */+class OoxmlDocxSliceTest {++ private fun docx(vararg entries: Pair<String, String>, name: String = "t.docx"): OdfDocument.TextDocument {+ 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(), name) as OdfDocument.TextDocument+ }++ private fun paras(doc: OdfDocument.TextDocument) =+ doc.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }++ private fun body(vararg inner: String) =+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body>${inner.joinToString("")}</w:body></w:document>"++ private fun para(text: String, ppr: String = "", rpr: String = "") =+ "<w:p>${if (ppr.isNotEmpty()) "<w:pPr>$ppr</w:pPr>" else ""}" ++ "<w:r>${if (rpr.isNotEmpty()) "<w:rPr>$rpr</w:rPr>" else ""}<w:t>$text</w:t></w:r></w:p>"++ // ---- Run formatting ----++ @Test fun runFormattingMaps() {+ val doc = docx("word/document.xml" to body(+ para("bi", rpr = "<w:b/><w:i/><w:strike/><w:sz w:val=\"24\"/>" ++ "<w:rFonts w:ascii=\"Arial\"/><w:vertAlign w:val=\"superscript\"/>" ++ "<w:spacing w:val=\"40\"/><w:lang w:val=\"en-US\"/>" ++ "<w:u w:val=\"single\" w:color=\"FF0000\"/><w:color w:val=\"00FF00\"/>")))+ val span = paras(doc)[0].spans[0]+ assertTrue(span.bold)+ assertTrue(span.italic)+ assertTrue(span.strikethrough)+ assertEquals(12f, span.fontSize)+ assertEquals("Arial", span.fontFamily)+ assertTrue(span.superscript)+ assertEquals(2f, span.letterSpacing)+ assertEquals("en", span.language)+ assertEquals("US", span.country)+ assertTrue(span.underline)+ assertEquals("solid", span.underlineStyle)+ assertEquals(0xFFFF0000L, span.underlineColor)+ assertEquals(0xFF00FF00L, span.color)+ }++ @Test fun vanishHidesRun() {+ val doc = docx("word/document.xml" to body(para("gone", rpr = "<w:vanish/>"), para("kept")))+ val texts = paras(doc).flatMap { it.spans }.map { it.text }+ assertFalse("gone" in texts)+ assertTrue("kept" in texts)+ }++ @Test fun capsMapsToUppercaseTransform() {+ val doc = docx("word/document.xml" to body(para("hi", rpr = "<w:caps/>")))+ assertEquals("uppercase", paras(doc)[0].spans[0].textTransform)+ val sc = docx("word/document.xml" to body(para("hi", rpr = "<w:smallCaps/>")))+ assertEquals("uppercase", paras(sc)[0].spans[0].textTransform)+ }++ @Test fun highlightAndShadeBackground() {+ val doc = docx("word/document.xml" to body(para("h", rpr = "<w:highlight w:val=\"yellow\"/>")))+ assertEquals(0xFFFFFF00L, paras(doc)[0].spans[0].backgroundColor)+ val shd = docx("word/document.xml" to body(para("s", rpr = "<w:shd w:fill=\"FF0000\"/>")))+ assertEquals(0xFFFF0000L, paras(shd)[0].spans[0].backgroundColor)+ }++ @Test fun subscriptTabsBreaksHyphens() {+ val sub = docx("word/document.xml" to body(+ para("a", rpr = "<w:vertAlign w:val=\"subscript\"/>")))+ assertTrue(paras(sub)[0].spans[0].subscript)+ // Build the run properly (avoids hand-nesting mistakes): tab, break, hyphens, symbol.+ val doc2 = docx("word/document.xml" to body(+ "<w:p><w:r><w:t>a</w:t></w:r><w:r><w:tab/></w:r><w:r><w:br/></w:r>" ++ "<w:r><w:noBreakHyphen/><w:softHyphen/><w:sym w:char=\"F02D\"/></w:r></w:p>"))+ val text = paras(doc2)[0].spans.joinToString("") { it.text }+ assertTrue(text.contains("\t"))+ assertTrue(text.contains("\n"))+ assertTrue(text.contains("‑"))+ assertTrue(text.contains(""))+ }++ @Test fun symPrintableFallback() {+ val doc = docx("word/document.xml" to body("<w:p><w:r><w:sym w:char=\"0041\"/></w:r></w:p>"))+ assertEquals("A", paras(doc)[0].spans[0].text)+ }++ // ---- Paragraph layout ----++ @Test fun paragraphAlignmentAndDirection() {+ val doc = docx("word/document.xml" to body(+ para("c", ppr = "<w:jc w:val=\"center\"/><w:bidi/>"),+ para("r", ppr = "<w:jc w:val=\"right\"/>"),+ para("j", ppr = "<w:jc w:val=\"both\"/>")))+ val ps = paras(doc)+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, ps[0].alignment)+ assertEquals(androidx.compose.ui.unit.LayoutDirection.Rtl, ps[0].direction)+ assertEquals(androidx.compose.ui.text.style.TextAlign.End, ps[1].alignment)+ assertEquals(androidx.compose.ui.text.style.TextAlign.Justify, ps[2].alignment)+ }++ @Test fun paragraphMarginsAndLineHeight() {+ val doc = docx("word/document.xml" to body(+ para("m", ppr = "<w:ind w:left=\"1440\" w:right=\"720\" w:firstLine=\"360\"/>" ++ "<w:spacing w:before=\"240\" w:after=\"120\" w:line=\"360\" w:lineRule=\"auto\"/>")))+ val p = paras(doc)[0]+ assertEquals(96f, p.marginLeft, 0.01f)+ assertEquals(48f, p.marginRight, 0.01f)+ assertEquals(24f, p.textIndent, 0.01f)+ assertEquals(16f, p.marginTop, 0.01f)+ assertEquals(8f, p.marginBottom, 0.01f)+ assertEquals(1.5f, p.lineHeightPercent ?: 0f, 0.001f)+ }++ @Test fun exactLineRuleGivesNoMultiplier() {+ val doc = docx("word/document.xml" to body(+ para("e", ppr = "<w:spacing w:line=\"480\" w:lineRule=\"exact\"/>")))+ assertNull(paras(doc)[0].lineHeightPercent)+ }++ @Test fun keepAndBreakFlags() {+ val doc = docx("word/document.xml" to body(+ para("k", ppr = "<w:keepNext/><w:keepLines/><w:widowControl w:val=\"0\"/>" ++ "<w:pageBreakBefore w:val=\"1\"/>")))+ val p = paras(doc)[0]+ assertTrue(p.keepWithNext)+ assertTrue(p.keepTogether)+ assertTrue(p.breakBeforePage)+ assertNull(p.widows)+ }++ @Test fun shadingBordersTabsDropCap() {+ val doc = docx("word/document.xml" to body(+ para("s", ppr = "<w:shd w:fill=\"00FF00\"/>" ++ "<w:pBdr><w:top w:val=\"single\" w:sz=\"8\" w:color=\"FF0000\"/></w:pBdr>" ++ "<w:tabs><w:tab w:val=\"center\" w:pos=\"1440\" w:leader=\"dot\"/>" ++ "<w:tab w:val=\"clear\" w:pos=\"100\"/></w:tabs>" ++ "<w:framePr w:dropCap=\"drop\" w:lines=\"2\"/>")))+ val p = paras(doc)[0]+ assertEquals(0xFF00FF00L, p.backgroundColor)+ assertNotNull(p.borders)+ assertEquals(0xFFFF0000L, p.borderColor)+ assertEquals(1, p.tabStops.size)+ assertEquals(96f, p.tabStops[0], 0.01f)+ assertEquals("center", p.tabStopDetails[0].type)+ assertEquals(".", p.tabStopDetails[0].leaderChar)+ assertEquals(2, p.dropCapLines)+ }++ @Test fun outlineLevelMapsToHeading() {+ val doc = docx("word/document.xml" to body(+ para("h", ppr = "<w:outlineLvl w:val=\"1\"/>")))+ assertEquals(ParagraphStyle.HEADING2, paras(doc)[0].style)+ }++ // ---- Styles inheritance ----++ @Test fun styleInheritanceBoldFromBasedOn() {+ val styles = "<w:styles xmlns:w=\"w\">" ++ "<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val=\"20\"/></w:rPr></w:rPrDefault></w:docDefaults>" ++ "<w:style w:styleId=\"Base\" w:type=\"paragraph\"><w:rPr><w:b/></w:rPr></w:style>" ++ "<w:style w:styleId=\"Child\" w:type=\"paragraph\"><w:basedOn w:val=\"Base\"/>" ++ "<w:rPr><w:i/></w:rPr></w:style></w:styles>"+ val doc = docx(+ "word/document.xml" to body(para("x", ppr = "<w:pStyle w:val=\"Child\"/>")),+ "word/styles.xml" to styles)+ val span = paras(doc)[0].spans[0]+ assertTrue(span.bold)+ assertTrue(span.italic)+ assertEquals(10f, span.fontSize)+ }++ @Test fun characterStyleApplies() {+ val styles = "<w:styles xmlns:w=\"w\">" ++ "<w:style w:styleId=\"Em\" w:type=\"character\"><w:rPr><w:i/><w:color w:val=\"FF0000\"/></w:rPr></w:style></w:styles>"+ val doc = docx(+ "word/document.xml" to body("<w:p><w:r><w:rPr><w:rStyle w:val=\"Em\"/></w:rPr><w:t>e</w:t></w:r></w:p>"),+ "word/styles.xml" to styles)+ val span = paras(doc)[0].spans[0]+ assertTrue(span.italic)+ assertEquals(0xFFFF0000L, span.color)+ }++ @Test fun underlineAndNumberingMaps() {+ assertEquals("solid", OoxmlDocxStyles.mapUnderline(null))+ assertEquals("none", OoxmlDocxStyles.mapUnderline("none"))+ assertEquals("double", OoxmlDocxStyles.mapUnderline("double"))+ assertEquals("dotted", OoxmlDocxStyles.mapUnderline("dottedHeavy"))+ assertEquals("dash", OoxmlDocxStyles.mapUnderline("dashLong"))+ assertEquals("wave", OoxmlDocxStyles.mapUnderline("wavyDouble"))+ assertEquals("solid", OoxmlDocxStyles.mapUnderline("weird"))+ assertEquals("a", OoxmlDocxStyles.mapNumFmt("lowerLetter"))+ assertEquals("A", OoxmlDocxStyles.mapNumFmt("upperLetter"))+ assertEquals("i", OoxmlDocxStyles.mapNumFmt("lowerRoman"))+ assertEquals("I", OoxmlDocxStyles.mapNumFmt("upperRoman"))+ assertEquals("1", OoxmlDocxStyles.mapNumFmt("decimal"))+ assertEquals("1", OoxmlDocxStyles.mapNumFmt("mystery"))+ assertEquals("•", OoxmlDocxStyles.mapBullet("\uF0B7"))+ assertEquals("◦", OoxmlDocxStyles.mapBullet("o"))+ assertEquals("•", OoxmlDocxStyles.mapBullet(""))+ }++ // ---- Fields, hyperlinks, bookmarks ----++ @Test fun pageFieldAnnotatesResult() {+ val doc = docx("word/document.xml" to body(+ "<w:p><w:r><w:fldChar w:fldCharType=\"begin\"/></w:r>" ++ "<w:r><w:instrText> PAGE </w:instrText></w:r>" ++ "<w:r><w:fldChar w:fldCharType=\"separate\"/></w:r>" ++ "<w:r><w:t>3</w:t></w:r>" ++ "<w:r><w:fldChar w:fldCharType=\"end\"/></w:r></w:p>"))+ assertEquals("page-number", paras(doc)[0].spans[0].field)+ }++ @Test fun hyperlinkFieldTarget() {+ val doc = docx("word/document.xml" to body(+ "<w:p><w:r><w:fldChar w:fldCharType=\"begin\"/></w:r>" ++ "<w:r><w:instrText> HYPERLINK \"https://x.test\" </w:instrText></w:r>" ++ "<w:r><w:fldChar w:fldCharType=\"separate\"/></w:r>" ++ "<w:r><w:t>link</w:t></w:r>" ++ "<w:r><w:fldChar w:fldCharType=\"end\"/></w:r></w:p>"))+ assertEquals("https://x.test", paras(doc)[0].spans[0].href)+ }++ @Test fun hyperlinkRelAndBookmarkAnchor() {+ val doc = docx(+ "word/document.xml" to body(+ "<w:p><w:hyperlink r:id=\"rId5\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<w:r><w:t>ext</w:t></w:r></w:hyperlink></w:p>" ++ "<w:p><w:bookmarkStart w:name=\"Top\"/><w:r><w:t>b</w:t></w:r></w:p>" ++ "<w:p><w:hyperlink w:anchor=\"Top\"><w:r><w:t>jump</w:t></w:r></w:hyperlink></w:p>"),+ "word/_rels/document.xml.rels" to (+ "<Relationships xmlns=\"urn:r\"><Relationship Id=\"rId5\" " ++ "Type=\"http://t/hyperlink\" Target=\"https://e.test\" TargetMode=\"External\"/></Relationships>"))+ val ps = paras(doc)+ assertEquals("https://e.test", ps[0].spans[0].href)+ assertEquals(listOf("Top"), doc.bookmarks.map { it.name })+ val jump = ps[2].spans[0]+ assertEquals("#Top", jump.href)+ }++ @Test fun hyperlinkMissingRelFallsBackToAnchor() {+ // r:id with no matching relationship + w:anchor: rel lookup misses, anchor wins.+ val doc = docx(+ "word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<w:body><w:p><w:hyperlink r:id=\"missing\" w:anchor=\"Top\">" ++ "<w:r><w:t>jump</w:t></w:r></w:hyperlink></w:p></w:body></w:document>"),+ "word/_rels/document.xml.rels" to (+ "<Relationships xmlns=\"urn:r\"><Relationship Id=\"other\" " ++ "Type=\"http://t/hyperlink\" Target=\"https://e.test\" TargetMode=\"External\"/></Relationships>"))+ assertEquals("#Top", paras(doc)[0].spans[0].href)+ }++ @Test fun hyperlinkAnchorOnlyLinksFragment() {+ // Anchor without any r:id: href becomes the #fragment form (internal bookmark link).+ val doc = docx("word/document.xml" to body(+ "<w:p><w:hyperlink w:anchor=\"Top\">" ++ "<w:r><w:t>jump</w:t></w:r></w:hyperlink></w:p>"))+ val jump = paras(doc)[0].spans.first { it.text == "jump" }+ assertEquals("#Top", jump.href)+ }++ @Test fun sdtInlineUnwrapsRuns() {+ val doc = docx("word/document.xml" to body(+ "<w:p><w:sdt><w:sdtContent><w:r><w:t>control</w:t></w:r></w:sdtContent></w:sdt></w:p>"))+ assertEquals("control", paras(doc)[0].spans[0].text)+ }++ // ---- Sections / page setup ----++ @Test fun sectionPageSetupAndColumns() {+ val doc = docx("word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body><w:p><w:r><w:t>x</w:t></w:r></w:p>" ++ "<w:sectPr><w:pgSz w:w=\"12240\" w:h=\"15840\" w:orient=\"portrait\"/>" ++ "<w:pgMar w:left=\"1440\" w:right=\"1440\" w:top=\"1440\" w:bottom=\"1440\"/>" ++ "<w:cols w:num=\"2\"/></w:sectPr></w:body></w:document>"))+ assertNotNull(doc.pageSetup)+ assertEquals(816f, doc.pageSetup!!.widthPx, 1f)+ val section = doc.content.filterIsInstance<OdfContentBlock.SectionStart>().firstOrNull()+ assertNotNull(section)+ assertEquals(2, section!!.columnCount)+ }++ @Test fun landscapeSwapsDimensions() {+ val doc = docx("word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body><w:p><w:r><w:t>x</w:t></w:r></w:p>" ++ "<w:sectPr><w:pgSz w:w=\"10000\" w:h=\"20000\" w:orient=\"landscape\"/></w:sectPr></w:body></w:document>"))+ assertTrue(doc.pageSetup!!.widthPx > doc.pageSetup!!.heightPx)+ }++ // ---- Footnotes / endnotes / comments ----++ @Test fun footnoteReferenceResolves() {+ val doc = docx(+ "word/document.xml" to body(+ "<w:p><w:r><w:t>text</w:t></w:r><w:r><w:footnoteReference w:id=\"1\"/></w:r></w:p>"),+ "word/footnotes.xml" to (+ "<w:footnotes xmlns:w=\"w\"><w:footnote w:id=\"1\">" ++ "<w:p><w:r><w:t>note body</w:t></w:r></w:p></w:footnote>" ++ "<w:footnote w:id=\"0\" w:type=\"separator\"><w:p/></w:footnote></w:footnotes>"))+ assertEquals(1, doc.footnotes.size)+ assertEquals("1", doc.footnotes[0].citation)+ assertEquals("note body", doc.footnotes[0].body[0].spans[0].text)+ val spans = paras(doc)[0].spans+ assertTrue(spans.any { it.superscript && it.text == "1" })+ }++ @Test fun commentXmlParsesToAnnotationMap() {+ // parseComments builds author/date/body maps from comments.xml (wiring the map to+ // spans happens elsewhere); cover the parse including multi-paragraph bodies.+ val doc = docx(+ "word/document.xml" to body(para("text")),+ "word/comments.xml" to (+ "<w:comments xmlns:w=\"w\"><w:comment w:id=\"0\" w:author=\"Al\" w:date=\"2024-05-01\">" ++ "<w:p><w:r><w:t>fix</w:t></w:r></w:p>" ++ "<w:p><w:r><w:t>this</w:t></w:r></w:p></w:comment></w:comments>"))+ assertEquals(listOf("text"), paras(doc).map { it.spans[0].text })+ }++ // ---- Tracked changes ----++ @Test fun insertionsAndDeletionsTracked() {+ val doc = docx("word/document.xml" to body(+ "<w:p><w:ins w:author=\"Al\" w:date=\"2024-01-01\"><w:r><w:t>new</w:t></w:r></w:ins>" ++ "<w:del w:author=\"Bo\"><w:r><w:t>old</w:t></w:r></w:del></w:p>"))+ assertEquals(2, doc.changes.size)+ val kinds = doc.changes.map { it.type }.toSet()+ assertEquals(setOf("insertion", "deletion"), kinds)+ val spans = paras(doc)[0].spans+ assertEquals("insertion", spans.first { it.text == "new" }.changeKind)+ assertEquals("deletion", spans.first { it.text == "old" }.changeKind)+ assertEquals("Al", doc.changes.first { it.type == "insertion" }.author)+ }++ // ---- Headers / footers ----++ @Test fun headerFooterImport() {+ val doc = docx(+ "word/document.xml" to body(para("body")),+ "word/_rels/document.xml.rels" to (+ "<Relationships xmlns=\"urn:r\">" ++ "<Relationship Id=\"h1\" Type=\"http://t/header\" Target=\"header1.xml\"/>" ++ "<Relationship Id=\"f1\" Type=\"http://t/footer\" Target=\"footer1.xml\"/></Relationships>"),+ "word/header1.xml" to body(para("head text")),+ "word/footer1.xml" to body(para("foot text")))+ assertEquals("head text", doc.headerParagraphs[0].spans[0].text)+ assertEquals("foot text", doc.footerParagraphs[0].spans[0].text)+ }++ // ---- Tables ----++ @Test fun tableWithMergesAndHeader() {+ val doc = docx("word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body><w:tbl>" ++ "<w:tblGrid><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"2000\"/></w:tblGrid>" ++ "<w:tblPr><w:tblBorders><w:top w:val=\"single\" w:sz=\"4\" w:color=\"000000\"/></w:tblBorders></w:tblPr>" ++ "<w:tr><w:trPr><w:tblHeader/></w:trPr>" ++ "<w:tc><w:tcPr><w:gridSpan w:val=\"2\"/><w:shd w:fill=\"FFFF00\"/></w:tcPr>" ++ "<w:p><w:r><w:t>wide</w:t></w:r></w:p></w:tc></w:tr>" ++ "<w:tr><w:tc><w:tcPr><w:vMerge w:val=\"restart\"/><w:vAlign w:val=\"center\"/></w:tcPr>" ++ "<w:p><w:r><w:t>tall</w:t></w:r></w:p></w:tc>" ++ "<w:tc><w:p><w:r><w:t>r</w:t></w:r></w:p></w:tc></w:tr>" ++ "<w:tr><w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc>" ++ "<w:tc><w:p><w:r><w:t>r2</w:t></w:r></w:p></w:tc></w:tr>" ++ "</w:tbl></w:body></w:document>"))+ val table = doc.content.filterIsInstance<OdfContentBlock.Table>()[0].table+ assertEquals(1, table.headerRowCount)+ assertEquals(2, table.rows[0].cells[0].colSpan)+ assertTrue(table.rows[0].cells[1].isCovered)+ assertEquals(0xFFFFFF00L, table.rows[0].cells[0].backgroundColor)+ assertEquals(2, table.rows[1].cells[0].rowSpan)+ assertTrue(table.rows[2].cells[0].isCovered)+ assertEquals("middle", table.rows[1].cells[0].verticalAlign)+ assertEquals(2, table.columns.size)+ assertNotNull(table.rows[1].cells[1].borders)+ }++ @Test fun nestedTableFlattens() {+ val doc = docx("word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body><w:tbl><w:tr><w:tc>" ++ "<w:p><w:r><w:t>outer</w:t></w:r></w:p>" ++ "<w:tbl><w:tr><w:tc><w:p><w:r><w:t>inner</w:t></w:r></w:p></w:tc></w:tr></w:tbl>" ++ "</w:tc></w:tr></w:tbl></w:body></w:document>"))+ val table = doc.content.filterIsInstance<OdfContentBlock.Table>()[0].table+ val texts = table.rows[0].cells[0].paragraphs.map { it.spans[0].text }+ assertTrue("outer" in texts)+ assertTrue("inner" in texts)+ }++ @Test fun tableCellBorderColorAndEmptyCell() {+ // tcBorders without top/left falls back to the first edge color; a paragraph-less+ // cell still yields one empty paragraph (covers toModel's empty/border branches).+ val doc = docx("word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body><w:tbl>" ++ "<w:tr><w:tc><w:tcPr><w:tcBorders>" ++ "<w:top w:val=\"single\" w:sz=\"4\" w:color=\"FF0000\"/>" ++ "</w:tcBorders></w:tcPr><w:p><w:r><w:t>c</w:t></w:r></w:p></w:tc>" ++ "<w:tc><w:tcPr/></w:tc></w:tr>" ++ "</w:tbl></w:body></w:document>"))+ val row = doc.content.filterIsInstance<OdfContentBlock.Table>()[0].table.rows[0]+ assertEquals(0xFFFF0000L, row.cells[0].borderColor)+ assertNotNull(row.cells[0].borders)+ assertEquals(1, row.cells[1].paragraphs.size)+ assertEquals("", row.cells[1].paragraphs[0].spans[0].text)+ }++ // ---- Drawings: image, chart, textbox, smartart ----++ @Test fun inlineImageFromDrawing() {+ val png = java.util.Base64.getDecoder().decode("iVBORw0KGgo=")+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ zos.putNextEntry(java.util.zip.ZipEntry("word/document.xml"))+ zos.write(body(+ "<w:p><w:r><w:drawing><wp:inline xmlns:wp=\"wp\">" ++ "<wp:extent cx=\"914400\" cy=\"457200\"/>" ++ "<wp:docPr name=\"pic\" descr=\"a pic\"/>" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData>" ++ "<pic:pic xmlns:pic=\"pic\"><pic:blipFill><a:blip r:embed=\"rId6\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" ++ "</pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"+ ).toByteArray(Charsets.UTF_8))+ zos.closeEntry()+ zos.putNextEntry(java.util.zip.ZipEntry("word/media/p.png"))+ zos.write(png)+ zos.closeEntry()+ zos.putNextEntry(java.util.zip.ZipEntry("word/_rels/document.xml.rels"))+ zos.write(("<Relationships xmlns=\"urn:r\"><Relationship Id=\"rId6\" Type=\"http://t/image\" " ++ "Target=\"media/p.png\"/></Relationships>").toByteArray(Charsets.UTF_8))+ zos.closeEntry()+ }+ val doc = OoxmlImporter.import(bos.toByteArray(), "img.docx") as OdfDocument.TextDocument+ val img = doc.content.filterIsInstance<OdfContentBlock.Image>().firstOrNull()+ assertNotNull(img)+ assertEquals(96f, img!!.image.width, 0.5f)+ assertEquals("a pic", img.image.altDesc)+ assertTrue(doc.images.containsKey(img.image.path))+ }++ @Test fun drawingChartBecomesBlock() {+ val doc = docx(+ "word/document.xml" to body(+ "<w:p><w:r><w:drawing><wp:inline xmlns:wp=\"wp\"><wp:extent cx=\"100\" cy=\"100\"/>" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData>" ++ "<c:chart xmlns:c=\"c\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"rId9\"/>" ++ "</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"),+ "word/_rels/document.xml.rels" to (+ "<Relationships xmlns=\"urn:r\"><Relationship Id=\"rId9\" Type=\"http://t/chart\" Target=\"charts/c1.xml\"/></Relationships>"),+ "word/charts/c1.xml" to (+ "<chartSpace><chart><plotArea><barChart>" ++ "<ser><tx><v>S</v></tx>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>1</v></pt></numCache></numRef></val></ser>" ++ "</barChart></plotArea></chart></chartSpace>"))+ assertEquals(1, doc.content.filterIsInstance<OdfContentBlock.Chart>().size)+ }++ @Test fun textboxContentSurfaces() {+ val doc = docx("word/document.xml" to body(+ "<w:p><w:r><w:drawing><wp:anchor xmlns:wp=\"wp\">" ++ "<w:txbxContent xmlns:w=\"w\"><w:p><w:r><w:t>boxed</w:t></w:r></w:p></w:txbxContent>" ++ "</wp:anchor></w:drawing></w:r></w:p>"))+ assertTrue(paras(doc).any { it.spans.any { s -> s.text == "boxed" } })+ }++ @Test fun drawingCropAndMetaMapToImage() {+ // srcRect crop percentages + docPr title/descr + xfrm rotation land on the image model.+ val png = java.util.Base64.getDecoder().decode("iVBORw0KGgo=")+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ zos.putNextEntry(java.util.zip.ZipEntry("word/document.xml"))+ zos.write(body(+ "<w:p><w:r><w:drawing><wp:inline xmlns:wp=\"wp\">" ++ "<wp:extent cx=\"914400\" cy=\"914400\"/>" ++ "<wp:docPr name=\"titled\" descr=\"described\"/>" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData>" ++ "<pic:pic xmlns:pic=\"pic\"><pic:blipFill>" ++ "<a:blip r:embed=\"rId7\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<a:srcRect l=\"10000\" t=\"20000\" r=\"5000\" b=\"0\"/></a:blip>" ++ "</pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline>" ++ "</w:drawing></w:r></w:p>"+ ).toByteArray(Charsets.UTF_8))+ zos.closeEntry()+ zos.putNextEntry(java.util.zip.ZipEntry("word/media/q.png"))+ zos.write(png)+ zos.closeEntry()+ zos.putNextEntry(java.util.zip.ZipEntry("word/_rels/document.xml.rels"))+ zos.write(("<Relationships xmlns=\"urn:r\"><Relationship Id=\"rId7\" Type=\"http://t/image\" " ++ "Target=\"media/q.png\"/></Relationships>").toByteArray(Charsets.UTF_8))+ zos.closeEntry()+ }+ val doc = OoxmlImporter.import(bos.toByteArray(), "crop.docx") as OdfDocument.TextDocument+ val img = doc.content.filterIsInstance<OdfContentBlock.Image>().firstOrNull()+ assertNotNull(img)+ assertEquals(0.1f, img!!.image.cropLeftPct, 0.001f)+ assertEquals(0.2f, img.image.cropTopPct, 0.001f)+ assertEquals(0.05f, img.image.cropRightPct, 0.001f)+ assertEquals(0f, img.image.cropBottomPct, 0.001f)+ assertEquals("titled", img.image.altTitle)+ assertEquals("described", img.image.altDesc)+ }++ @Test fun smartArtTextSurfacesWithoutVisual() {+ // A drawing with only a diagram relId falls back to SmartArt text extraction.+ val doc = docx(+ "word/document.xml" to body(+ "<w:p><w:r><w:drawing><wp:inline xmlns:wp=\"wp\">" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData>" ++ "<dgm:relIds xmlns:dgm=\"d\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:dm=\"rId8\"/>" ++ "</a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"),+ "word/_rels/document.xml.rels" to (+ "<Relationships xmlns=\"urn:r\"><Relationship Id=\"rId8\" " ++ "Type=\"http://t/diagramData\" Target=\"diagrams/data1.xml\"/></Relationships>"),+ "word/diagrams/data1.xml" to (+ "<dgm:dataModel xmlns:dgm=\"d\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" ++ "<dgm:pt><dgm:prSet/><a:p><a:t>smart</a:t></a:p></dgm:pt>" ++ "<dgm:pt><dgm:prSet/><a:p><a:t>art</a:t></a:p></dgm:pt>" ++ "</dgm:dataModel>"))+ assertTrue(paras(doc).any { it.spans.any { s -> s.text == "smart" } })+ assertTrue(paras(doc).any { it.spans.any { s -> s.text == "art" } })+ }++ // ---- Numbering edge: bullet + start override ----++ @Test fun bulletListAndCustomStart() {+ val doc = docx(+ "word/document.xml" to body(+ "<w:p><w:pPr><w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"5\"/></w:numPr></w:pPr>" ++ "<w:r><w:t>dot</w:t></w:r></w:p>"),+ "word/numbering.xml" to (+ "<w:numbering xmlns:w=\"w\"><w:abstractNum w:abstractNumId=\"7\">" ++ "<w:lvl w:ilvl=\"0\"><w:start w:val=\"3\"/><w:numFmt w:val=\"bullet\"/>" ++ "<w:lvlText w:val=\"\uF0B7\"/></w:lvl></w:abstractNum>" ++ "<w:num w:numId=\"5\"><w:abstractNumId w:val=\"7\"/></w:num></w:numbering>"))+ val p = paras(doc)[0]+ assertEquals(ListType.BULLET, p.listType)+ assertEquals("•", p.listBulletChar)+ }++ @Test fun themeTintColorResolves() {+ val doc = docx(+ "word/document.xml" to body(para("t", rpr = "<w:color w:themeColor=\"accent1\"/>")),+ "word/theme/theme1.xml" to (+ "<theme><themeElements><clrScheme name=\"X\">" ++ "<accent1><srgbClr val=\"4472C4\"/></accent1></clrScheme>" ++ "</themeElements></theme>"))+ assertEquals(0xFF4472C4L, paras(doc)[0].spans[0].color)+ }++ @Test fun emptyDocWithoutPartGivesEmpty() {+ val doc = docx("other.xml" to "<x/>")+ assertTrue(doc.content.isEmpty())+ }++ @Test fun omathParaBecomesFormula() {+ val doc = docx("word/document.xml" to (+ "<w:document xmlns:w=\"w\" xmlns:m=\"m\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><w:body>" ++ "<m:oMathPara><m:oMath><m:r><m:t>x</m:t></m:r></m:oMath></m:oMathPara>" ++ "</w:body></w:document>"))+ val f = doc.content.filterIsInstance<OdfContentBlock.Formula>().firstOrNull()+ assertNotNull(f)+ assertTrue(f!!.mathml.contains("<math"))+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlPackageSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlPackageSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlPackageSliceTest.ktnew file mode 100644index 0000000000..38ebaf5964--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlPackageSliceTest.kt@@ -0,0 +1,268 @@+package com.vayunmathur.office.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): tests for the OOXML package layer — [OoxmlPackage] zip reading, path+ * normalization, relationship resolution, content-type lookup, media handling — plus the+ * [OoxmlImporter] entry point (format dispatch, zip/OLE sniffing, encrypted-file guards,+ * best-effort fallback).+ */+class OoxmlPackageSliceTest {++ private fun zip(vararg entries: Pair<String, ByteArray>): ByteArray {+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ for ((name, content) in entries) {+ zos.putNextEntry(java.util.zip.ZipEntry(name))+ zos.write(content)+ zos.closeEntry()+ }+ }+ return bos.toByteArray()+ }++ private fun zipText(vararg entries: Pair<String, String>) =+ zip(*entries.map { (k, v) -> k to v.toByteArray(Charsets.UTF_8) }.toTypedArray())++ // ---- normalize ----++ @Test fun normalizeRelative() {+ assertEquals("word/media/a.png", OoxmlPackage.normalize("word/document.xml", "media/a.png"))+ assertEquals("media/a.png", OoxmlPackage.normalize("word/document.xml", "../media/a.png"))+ assertEquals("xl/styles.xml", OoxmlPackage.normalize("xl/workbook.xml", "/xl/styles.xml"))+ assertEquals("word/a.png", OoxmlPackage.normalize("word/document.xml", "./a.png"))+ assertEquals("word/a.png", OoxmlPackage.normalize("word/document.xml", "sub/../a.png"))+ // Climbing past the root stays at root.+ assertEquals("a.png", OoxmlPackage.normalize("document.xml", "../../a.png"))+ // Root-level part with a bare target.+ assertEquals("styles.xml", OoxmlPackage.normalize("workbook.xml", "styles.xml"))+ }++ // ---- read: entries vs media, BOM strip, robustness ----++ @Test fun readSplitsTextAndMedia() {+ val png = byteArrayOf(1.toByte(), 2.toByte(), 3.toByte())+ val pkg = OoxmlPackage.read(zipText("word/document.xml" to "<w:doc/>") + byteArrayOf())+ assertTrue(pkg.entries.containsKey("word/document.xml"))+ assertTrue(pkg.media.isEmpty())+ val pkg2 = OoxmlPackage.read(zip("word/media/i.png" to png, "word/document.xml" to "<w:doc/>".toByteArray()))+ assertTrue(pkg2.media.containsKey("word/media/i.png"))+ assertEquals(png.toList(), pkg2.media["word/media/i.png"]!!.toList())+ }++ @Test fun readIgnoresNonXmlNonMedia() {+ val pkg = OoxmlPackage.read(zipText("word/document.xml" to "<w:doc/>", "notes.txt" to "hi"))+ assertTrue(pkg.entries.containsKey("word/document.xml"))+ assertFalse(pkg.entries.containsKey("notes.txt"))+ }++ @Test fun readStripsBom() {+ val withBom = "\uFEFF<w:document/>".toByteArray(Charsets.UTF_8)+ val pkg = OoxmlPackage.read(zip("word/document.xml" to withBom))+ assertEquals("<w:document/>", pkg.entries["word/document.xml"])+ }++ @Test fun readNeverThrowsOnGarbage() {+ val pkg = OoxmlPackage.read(byteArrayOf(9, 8, 7, 6, 5))+ assertTrue(pkg.entries.isEmpty())+ assertTrue(pkg.media.isEmpty())+ val empty = OoxmlPackage.read(ByteArray(0))+ assertTrue(empty.entries.isEmpty())+ }++ @Test fun readMediaExtensionsCaseInsensitive() {+ val pkg = OoxmlPackage.read(zip("word/media/PHOTO.JPG" to byteArrayOf(1), "word/document.xml" to "<x/>".toByteArray()))+ assertTrue(pkg.media.containsKey("word/media/PHOTO.JPG"))+ val svg = OoxmlPackage.read(zip("word/media/v.SVG" to byteArrayOf(2), "word/document.xml" to "<x/>".toByteArray()))+ assertTrue(svg.media.containsKey("word/media/v.SVG"))+ }++ // ---- relsFor / resolve ----++ private val relsXml = "<Relationships xmlns=\"urn:r\">" ++ "<Relationship Id=\"rId1\" Type=\"http://t/wordprocessingml/header\" Target=\"header1.xml\"/>" ++ "<Relationship Id=\"rId2\" Type=\"http://t/hyperlink\" Target=\"https://example.com\" TargetMode=\"External\"/>" ++ "<Relationship Id=\"rId3\" Type=\"http://t/image\" Target=\"../media/i.png\"/>" ++ "</Relationships>"++ @Test fun relsResolveInternalAndExternal() {+ val pkg = OoxmlPackage(+ mapOf("word/_rels/document.xml.rels" to relsXml),+ emptyMap())+ val rels = pkg.relsFor("word/document.xml")+ assertEquals(3, rels.size)+ assertEquals("word/header1.xml", rels["rId1"]!!.target)+ assertFalse(rels["rId1"]!!.external)+ assertEquals("https://example.com", rels["rId2"]!!.target)+ assertTrue(rels["rId2"]!!.external)+ assertEquals("media/i.png", rels["rId3"]!!.target)+ // resolve() helper.+ assertEquals("word/header1.xml", pkg.resolve("word/document.xml", "rId1"))+ assertEquals("https://example.com", pkg.resolve("word/document.xml", "rId2"))+ assertNull(pkg.resolve("word/document.xml", "nope"))+ assertNull(pkg.resolve("word/document.xml", null))+ }++ @Test fun relsMissingFileGivesEmpty() {+ val pkg = OoxmlPackage(emptyMap(), emptyMap())+ assertTrue(pkg.relsFor("word/document.xml").isEmpty())+ assertNull(pkg.resolve("word/document.xml", "rId1"))+ }++ @Test fun relsSkipsEntriesMissingIdOrTarget() {+ val bad = "<Relationships xmlns=\"urn:r\">" ++ "<Relationship Type=\"http://t/x\" Target=\"a.xml\"/>" ++ "<Relationship Id=\"rX\" Type=\"http://t/x\"/>" ++ "<Relationship Id=\"rOk\" Type=\"http://t/x\" Target=\"ok.xml\"/>" ++ "</Relationships>"+ val pkg = OoxmlPackage(mapOf("word/_rels/document.xml.rels" to bad), emptyMap())+ val rels = pkg.relsFor("word/document.xml")+ assertEquals(listOf("rOk"), rels.keys.toList())+ }++ @Test fun relsAtRootPath() {+ val pkg = OoxmlPackage(+ mapOf("_rels/document.xml.rels" to relsXml),+ emptyMap())+ assertEquals(3, pkg.relsFor("document.xml").size)+ }++ @Test fun relsAreCached() {+ val pkg = OoxmlPackage(+ mapOf("word/_rels/document.xml.rels" to relsXml),+ emptyMap())+ assertTrue(pkg.relsFor("word/document.xml") === pkg.relsFor("word/document.xml"))+ }++ // ---- mediaBytes ----++ @Test fun mediaBytesToleratesLeadingSlash() {+ val bytes = byteArrayOf(7)+ val pkg = OoxmlPackage(emptyMap(), mapOf("word/media/i.png" to bytes))+ assertTrue(pkg.mediaBytes("word/media/i.png") === bytes)+ assertTrue(pkg.mediaBytes("/word/media/i.png") === bytes)+ assertNull(pkg.mediaBytes(null))+ assertNull(pkg.mediaBytes("word/media/missing.png"))+ }++ // ---- partsOfType ----++ @Test fun partsOfTypeMatchesOverrides() {+ val ct = "<Types xmlns=\"urn:t\">" ++ "<Default Extension=\"png\" ContentType=\"image/png\"/>" ++ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.main.document\"/>" ++ "<Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.ms-excel.sheet\"/>" ++ "</Types>"+ val pkg = OoxmlPackage(mapOf("[Content_Types].xml" to ct), emptyMap())+ assertEquals(listOf("word/document.xml"), pkg.partsOfType("document"))+ assertEquals(listOf("xl/workbook.xml"), pkg.partsOfType("SHEET"))+ assertTrue(pkg.partsOfType("presentation").isEmpty())+ }++ @Test fun partsOfTypeWithoutContentTypes() {+ val pkg = OoxmlPackage(emptyMap(), emptyMap())+ assertTrue(pkg.partsOfType("document").isEmpty())+ }++ // ---- OoxmlImporter entry point ----++ private val minimalDocx = zipText(+ "word/document.xml" to "<w:document xmlns:w=\"w\"><w:body><w:p><w:r><w:t>Hi</w:t></w:r></w:p></w:body></w:document>"+ )++ @Test fun importDispatchesByExtension() {+ val doc = OoxmlImporter.import(minimalDocx, "memo.docx")+ assertTrue(doc is com.vayunmathur.library.ui.odf.OdfDocument.TextDocument)+ assertEquals("memo.docx", doc.title)+ val para = (doc.content[0] as com.vayunmathur.library.ui.odf.OdfContentBlock.Paragraph).paragraph+ assertEquals("Hi", para.spans[0].text)+ }++ @Test fun importDispatchesByContentWhenExtensionUnknown() {+ val doc = OoxmlImporter.import(minimalDocx, "mystery.bin")+ assertTrue(doc is com.vayunmathur.library.ui.odf.OdfDocument.TextDocument)+ }++ @Test fun importDocmExtension() {+ assertTrue(OoxmlImporter.import(minimalDocx, "m.docm") is com.vayunmathur.library.ui.odf.OdfDocument.TextDocument)+ }++ @Test fun importMinimalXlsxAndPptx() {+ val xlsx = zipText(+ "xl/workbook.xml" to "<workbook xmlns=\"s\"><sheets><sheet name=\"S\" sheetId=\"1\"/></sheets></workbook>",+ "xl/worksheets/sheet1.xml" to "<worksheet xmlns=\"s\"><sheetData><row r=\"1\"><c r=\"A1\"><v>5</v></c></row></sheetData></worksheet>"+ )+ val s = OoxmlImporter.import(xlsx, "b.xlsx")+ assertTrue(s is com.vayunmathur.library.ui.odf.OdfDocument.Spreadsheet)+ assertEquals(5.0, (s as com.vayunmathur.library.ui.odf.OdfDocument.Spreadsheet).sheets[0].rows[0].cells[0].numberValue!!, 0.0001)++ val pptx = zipText(+ "ppt/slides/slide1.xml" to "<p:sld xmlns:p=\"p\"><p:cSld><p:spTree/></p:cSld></p:sld>"+ )+ val p = OoxmlImporter.import(pptx, "d.pptx")+ assertTrue(p is com.vayunmathur.library.ui.odf.OdfDocument.Presentation)+ }++ @Test fun importUnknownReturnsNull() {+ assertNull(OoxmlImporter.import(zipText("a.txt" to "hello"), "notes.txt"))+ }++ @Test fun importPasswordProtectedThrows() {+ // OLE/CFB magic header.+ val ole = byteArrayOf(0xD0.toByte(), 0xCF.toByte(), 0x11.toByte(), 0xE0.toByte(), 0xA1.toByte(), 0xB1.toByte(), 0x1A.toByte(), 0xE1.toByte())+ try {+ OoxmlImporter.import(ole, "locked.docx")+ assertTrue(false, "expected IllegalArgumentException")+ } catch (e: IllegalArgumentException) {+ assertTrue(e.message!!.contains("password", ignoreCase = true))+ }+ assertTrue(OoxmlImporter.isEncryptedOfficeFile(ole))+ assertFalse(OoxmlImporter.isEncryptedOfficeFile(minimalDocx))+ assertFalse(OoxmlImporter.isEncryptedOfficeFile(ByteArray(0)))+ }++ @Test fun importEncryptionInfoEntryThrows() {+ val pkg = zipText(+ "EncryptionInfo" to "junk",+ "word/document.xml" to "<w:document xmlns:w=\"w\"><w:body/></w:document>"+ )+ try {+ OoxmlImporter.import(pkg, "locked.docx")+ assertTrue(false, "expected IllegalArgumentException")+ } catch (e: IllegalArgumentException) {+ assertTrue(e.message!!.contains("password", ignoreCase = true))+ }+ }++ @Test fun looksLikeOoxmlSniffs() {+ assertTrue(OoxmlImporter.looksLikeOoxml(minimalDocx))+ assertFalse(OoxmlImporter.looksLikeOoxml(zipText("a.txt" to "hi")))+ assertFalse(OoxmlImporter.looksLikeOoxml("not a zip".toByteArray()))+ assertFalse(OoxmlImporter.looksLikeOoxml(ByteArray(0)))+ }++ @Test fun importMalformedFallsBackToEmptyDoc() {+ // A docx part that parses as XML but has an unexpected shape still imports best-effort.+ val weird = zipText("word/document.xml" to "<w:document xmlns:w=\"w\"><w:body><w:p><w:r>")+ val doc = OoxmlImporter.import(weird, "weird.docx")+ // Either a real (possibly empty) doc or the empty fallback — but never null/crash.+ assertNotNull(doc)+ }++ @Test fun importEmptyZipFallsBackByExtension() {+ val emptyZip = zipText()+ val doc = OoxmlImporter.import(emptyZip, "empty.docx")+ assertTrue(doc is com.vayunmathur.library.ui.odf.OdfDocument.TextDocument)+ assertTrue(doc.content.isEmpty())+ val sheet = OoxmlImporter.import(emptyZip, "empty.xlsx")+ assertTrue(sheet is com.vayunmathur.library.ui.odf.OdfDocument.Spreadsheet)+ val pres = OoxmlImporter.import(emptyZip, "empty.pptx")+ assertTrue(pres is com.vayunmathur.library.ui.odf.OdfDocument.Presentation)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlPptxSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlPptxSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlPptxSliceTest.ktnew file mode 100644index 0000000000..2f6a799ff2--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlPptxSliceTest.kt@@ -0,0 +1,582 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.ListType+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.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): pptx importer tests ([OoxmlPptx], [OoxmlPptxText], [OoxmlPptxGroups],+ * [OoxmlPptxPlaceholders]) — slide order, shapes, fills/strokes/gradients, pictures,+ * groups, connectors, graphic frames (tables/charts/diagrams), text, notes, transitions,+ * backgrounds, placeholders.+ */+class OoxmlPptxSliceTest {++ private fun pptx(vararg entries: Pair<String, String>, name: String = "d.pptx"): OdfDocument.Presentation {+ 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(), name) as OdfDocument.Presentation+ }++ private fun slide(vararg inner: String) =+ "<p:sld xmlns:p=\"p\" xmlns:a=\"a\"><p:cSld><p:spTree>${inner.joinToString("")}</p:spTree></p:cSld></p:sld>"++ private fun shape(+ text: String = "Hello",+ bold: Boolean = true,+ geom: String = "rect",+ fill: String = "<a:solidFill><a:srgbClr val=\"FF0000\"/></a:solidFill>",+ extra: String = ""+ ) = "<p:sp><p:spPr><a:xfrm><a:off x=\"914400\" y=\"914400\"/>" ++ "<a:ext cx=\"1828800\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"$geom\"/>$fill</p:spPr>" ++ "<p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/><a:p><a:r><a:rPr b=\"${if (bold) 1 else 0}\" sz=\"2400\"/>" ++ "<a:t>$text</a:t></a:r></a:p></p:txBody>$extra</p:sp>"++ private fun frames(doc: OdfDocument.Presentation) =+ doc.slides[0].elements.filterIsInstance<OdfSlideElement.Frame>()++ // ---- Slide order / names / fallback ----++ @Test fun slideOrderFollowsPresentation() {+ val doc = pptx(+ "ppt/presentation.xml" to ("<p:presentation xmlns:p=\"p\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<p:sldIdLst><p:sldId r:id=\"s2\"/><p:sldId r:id=\"s1\"/></p:sldIdLst></p:presentation>"),+ "ppt/_rels/presentation.xml.rels" to ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"s1\" Type=\"http://t/slide\" Target=\"slides/slide1.xml\"/>" ++ "<Relationship Id=\"s2\" Type=\"http://t/slide\" Target=\"slides/slide2.xml\"/></Relationships>"),+ "ppt/slides/slide1.xml" to slide(shape("one")),+ "ppt/slides/slide2.xml" to slide(shape("two")))+ assertEquals(2, doc.slides.size)+ assertTrue(frames(doc)[0].frame.paragraphs[0].spans[0].text == "two")+ }++ @Test fun emptyPackageGivesPlaceholderSlide() {+ val doc = pptx("other.xml" to "<x/>")+ assertEquals(1, doc.slides.size)+ assertEquals("Slide 1", doc.slides[0].name)+ }++ @Test fun slideNameFromCSld() {+ val doc = pptx(+ "ppt/slides/slide1.xml" to (+ "<p:sld xmlns:p=\"p\"><p:cSld name=\"Intro\"><p:spTree/></p:cSld></p:sld>"))+ assertEquals("Intro", doc.slides[0].name)+ }++ // ---- Shapes ----++ @Test fun shapeTextAndFill() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(shape()))+ val frame = frames(doc)[0].frame+ val span = frame.paragraphs[0].spans[0]+ assertEquals("Hello", span.text)+ assertTrue(span.bold)+ assertEquals(24f, span.fontSize)+ assertEquals(0xFFFF0000L, frame.fillColor)+ assertEquals(96f, frame.x, 0.5f)+ assertEquals(192f, frame.width, 0.5f)+ }++ @Test fun ellipseLineAndRoundRect() {+ // Geometry-only shapes (no text) become Shape elements of the matching kind.+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ shape("", geom = "ellipse"),+ shape("", geom = "line", bold = false),+ shape("", geom = "roundRect")))+ val shapes = doc.slides[0].elements.filterIsInstance<OdfSlideElement.Shape>().map { it.shape }+ assertTrue(shapes.any { it is OdfShape.Ellipse })+ assertTrue(shapes.any { it is OdfShape.Line })+ assertTrue(shapes.any { it is OdfShape.Rect && it.cornerRadius > 0 })+ }++ @Test fun textBoxWithRectGeometryBecomesFrame() {+ // A rect carrying text renders as a text Frame (fills still apply).+ val doc = pptx("ppt/slides/slide1.xml" to slide(shape("caption", geom = "rect")))+ val frame = frames(doc)[0].frame+ assertEquals("caption", frame.paragraphs[0].spans[0].text)+ assertEquals(0xFFFF0000L, frame.fillColor)+ }++ @Test fun strokeAndDashAndGradient() {+ // A geometry WITH text renders as a Frame carrying the fill/stroke/gradient.+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:sp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"ellipse\"/>" ++ "<a:gradFill><a:gsLst><a:gs pos=\"0\"><a:srgbClr val=\"FF0000\"/></a:gs>" ++ "<a:gs pos=\"100000\"><a:srgbClr val=\"0000FF\"/></a:gs></a:gsLst>" ++ "<a:lin ang=\"5400000\"/></a:gradFill>" ++ "<a:ln w=\"12700\"><a:solidFill><a:srgbClr val=\"00FF00\"/></a:solidFill>" ++ "<a:prstDash val=\"dash\"/></a:ln></p:spPr>" ++ "<p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/><a:p><a:r><a:t>g</a:t></a:r></a:p></p:txBody></p:sp>"))+ val frame = frames(doc)[0].frame+ assertNotNull(frame.fillGradient)+ assertEquals(0xFFFF0000L, frame.fillGradient!!.startColor)+ assertEquals(0xFF0000FFL, frame.fillGradient!!.endColor)+ assertEquals(90f, frame.fillGradient!!.angle, 0.01f)+ assertEquals(0xFF00FF00L, frame.strokeColor)+ }++ @Test fun geometryOnlyEllipseBecomesShape() {+ // The same geometry WITHOUT text becomes a Shape element instead.+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:sp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"ellipse\"/>" ++ "<a:solidFill><a:srgbClr val=\"FF0000\"/></a:solidFill>" ++ "</p:spPr><p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/></p:txBody></p:sp>"))+ val el = doc.slides[0].elements.filterIsInstance<OdfSlideElement.Shape>()[0].shape+ assertTrue(el is OdfShape.Ellipse)+ assertEquals(0xFFFF0000L, el.fillColor)+ }++ @Test fun rotationAndFlipLine() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:sp><p:spPr><a:xfrm rot=\"5400000\" flipH=\"1\" flipV=\"1\">" ++ "<a:off x=\"0\" y=\"0\"/><a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"line\"/></p:spPr>" ++ "<p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/><a:p><a:r><a:t>l</a:t></a:r></a:p></p:txBody></p:sp>"))+ val frame = frames(doc)[0].frame+ assertEquals(90f, frame.rotationDegrees, 0.01f)+ }++ @Test fun helperFuns() {+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, OoxmlPptx.textAlignOf("ctr"))+ assertEquals(androidx.compose.ui.text.style.TextAlign.End, OoxmlPptx.textAlignOf("r"))+ assertEquals(androidx.compose.ui.text.style.TextAlign.Justify, OoxmlPptx.textAlignOf("just"))+ assertEquals(androidx.compose.ui.text.style.TextAlign.Start, OoxmlPptx.textAlignOf("l"))+ assertNull(OoxmlPptx.textAlignOf("weird"))+ assertNull(OoxmlPptx.textAlignOf(null))+ }++ // ---- Pictures ----++ @Test fun pictureImportsWithCrop() {+ val png = byteArrayOf(1, 2, 3)+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ fun add(n: String, c: ByteArray) {+ zos.putNextEntry(java.util.zip.ZipEntry(n)); zos.write(c); zos.closeEntry()+ }+ add("ppt/slides/slide1.xml", slide(+ "<p:pic><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm></p:spPr>" ++ "<p:cNvPr descr=\"alt\"/><p:blipFill><a:blip r:embed=\"rId1\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" ++ "<a:srcRect l=\"10000\" t=\"20000\" r=\"5000\" b=\"0\"/></p:blipFill></p:pic>"+ ).toByteArray(Charsets.UTF_8))+ add("ppt/slides/_rels/slide1.xml.rels", ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"rId1\" Type=\"http://t/image\" Target=\"../media/p.png\"/></Relationships>").toByteArray())+ add("ppt/media/p.png", png)+ }+ val doc = OoxmlImporter.import(bos.toByteArray(), "p.pptx") as OdfDocument.Presentation+ val frame = frames(doc)[0].frame+ assertNotNull(frame.image)+ assertEquals("alt", frame.image!!.altDesc)+ assertEquals(0.1f, frame.image!!.cropLeftPct, 0.001f)+ assertEquals(0.2f, frame.image!!.cropTopPct, 0.001f)+ assertTrue(doc.images.isNotEmpty())+ }++ @Test fun pictureWithoutMediaIsSkipped() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:pic><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm></p:spPr>" ++ "<p:blipFill><a:blip r:embed=\"rMissing\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/></p:blipFill></p:pic>"))+ assertTrue(doc.slides[0].elements.isEmpty())+ }++ // ---- Groups / connectors ----++ @Test fun groupTransformsChildren() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:grpSp><p:grpSpPr><a:xfrm xmlns:a=\"a\">" ++ "<a:off x=\"914400\" y=\"914400\"/><a:ext cx=\"1828800\" cy=\"914400\"/>" ++ "<a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"914400\" cy=\"914400\"/>" ++ "</a:xfrm></p:grpSpPr>" ++ shape("g") ++ "<p:grpSp><p:grpSpPr><a:xfrm xmlns:a=\"a\">" ++ "<a:off x=\"0\" y=\"0\"/><a:ext cx=\"914400\" cy=\"914400\"/>" ++ "<a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"914400\" cy=\"914400\"/>" ++ "</a:xfrm></p:grpSpPr>" + shape("nested") + "</p:grpSp>" ++ "</p:grpSp>"))+ // Outer group scales 2x and offsets; both shapes survive the transform.+ assertEquals(2, doc.slides[0].elements.size)+ }++ @Test fun groupHoldsPictureAndConnector() {+ // pic/cxnSp branches of applyGroupTag add transformed children like sp does.+ val png = java.util.Base64.getDecoder().decode("iVBORw0KGgo=")+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ fun add(n: String, c: ByteArray) {+ zos.putNextEntry(java.util.zip.ZipEntry(n)); zos.write(c); zos.closeEntry()+ }+ add("ppt/slides/slide1.xml", slide(+ "<p:grpSp><p:grpSpPr><a:xfrm xmlns:a=\"a\">" ++ "<a:off x=\"0\" y=\"0\"/><a:ext cx=\"914400\" cy=\"914400\"/>" ++ "<a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"914400\" cy=\"914400\"/>" ++ "</a:xfrm></p:grpSpPr>" ++ "<p:pic><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm></p:spPr>" ++ "<p:blipFill><a:blip r:embed=\"rId1\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" ++ "</p:blipFill></p:pic>" ++ "<p:cxnSp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"457200\"/></a:xfrm></p:spPr></p:cxnSp>" ++ "</p:grpSp>").toByteArray())+ add("ppt/slides/_rels/slide1.xml.rels", ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"rId1\" Type=\"http://t/image\" Target=\"../media/m.png\"/>" ++ "</Relationships>").toByteArray())+ add("ppt/media/m.png", png)+ }+ val doc = OoxmlImporter.import(bos.toByteArray(), "g.pptx")+ as OdfDocument.Presentation+ assertEquals(2, doc.slides[0].elements.size)+ }++ @Test fun connectorBecomesLine() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:cxnSp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"457200\"/></a:xfrm>" ++ "<a:ln><a:prstDash val=\"dash\"/></a:ln></p:spPr></p:cxnSp>"))+ val line = doc.slides[0].elements.filterIsInstance<OdfSlideElement.Shape>()[0].shape+ assertTrue(line is OdfShape.Line)+ assertTrue((line as OdfShape.Line).strokeDashed)+ }++ @Test fun connectorWithoutXfrmSkipped() {+ val doc = pptx("ppt/slides/slide1.xml" to slide("<p:cxnSp><p:spPr/></p:cxnSp>"))+ assertTrue(doc.slides[0].elements.isEmpty())+ }++ @Test fun groupTfComposeMath() {+ val p = OoxmlPptxGroups.GroupTf(2f, 10f, 3f, 20f)+ val out = p.apply(5f, 7f, 100f, 50f)+ assertEquals(20f, out[0])+ assertEquals(41f, out[1])+ assertEquals(200f, out[2])+ assertEquals(150f, out[3])+ val c = OoxmlPptxGroups.GroupTf.compose(p, OoxmlPptxGroups.GroupTf(4f, 1f, 5f, 2f))+ val chained = c.apply(1f, 1f, 1f, 1f)+ val manual = p.apply(4f * 1f + 1f, 5f * 1f + 2f, 4f, 5f)+ assertEquals(manual[0], chained[0])+ assertEquals(manual[1], chained[1])+ }++ // ---- Graphic frames: table / chart / diagram ----++ @Test fun slideTableFlattensToTabParagraphs() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:graphicFrame><a:xfrm xmlns:a=\"a\"><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData><a:tbl>" ++ "<a:tr><a:tc><a:txBody><a:p><a:r><a:t>A</a:t></a:r></a:p></a:txBody></a:tc>" ++ "<a:tc><a:txBody><a:p><a:r><a:t>B</a:t></a:r></a:p></a:txBody></a:tc></a:tr>" ++ "</a:tbl></a:graphicData></a:graphic></p:graphicFrame>"))+ val text = frames(doc)[0].frame.paragraphs[0].spans.joinToString("") { it.text }+ assertEquals("A\tB", text)+ }++ @Test fun graphicChartBecomesFrame() {+ val doc = pptx(+ "ppt/slides/slide1.xml" to slide(+ "<p:graphicFrame><a:xfrm xmlns:a=\"a\"><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData>" ++ "<c:chart xmlns:c=\"c\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"c1\"/>" ++ "</a:graphicData></a:graphic></p:graphicFrame>"),+ "ppt/slides/_rels/slide1.xml.rels" to (+ "<Relationships xmlns=\"p\"><Relationship Id=\"c1\" Type=\"http://t/chart\" Target=\"../charts/c1.xml\"/></Relationships>"),+ "ppt/charts/c1.xml" to ("<chartSpace><chart><plotArea><barChart>" ++ "<ser><tx><v>S</v></tx>" ++ "<val><numRef><numCache><pt idx=\"0\"><v>2</v></pt></numCache></numRef></val></ser>" ++ "</barChart></plotArea></chart></chartSpace>"))+ val frame = frames(doc)[0].frame+ assertNotNull(frame.chart)+ assertEquals(listOf(2f), frame.chart!!.series[0].values)+ }++ @Test fun graphicDiagramTextSurfaces() {+ val aNs = "http://schemas.openxmlformats.org/drawingml/2006/main"+ val doc = pptx(+ "ppt/slides/slide1.xml" to slide(+ "<p:graphicFrame><a:xfrm xmlns:a=\"a\"><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:graphic xmlns:a=\"a\"><a:graphicData>" ++ "<dgm:relIds xmlns:dgm=\"d\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:dm=\"dm1\"/>" ++ "</a:graphicData></a:graphic></p:graphicFrame>"),+ "ppt/slides/_rels/slide1.xml.rels" to (+ "<Relationships xmlns=\"p\"><Relationship Id=\"dm1\" Type=\"http://t/diagram\" Target=\"../diagrams/d1.xml\"/></Relationships>"),+ "ppt/diagrams/d1.xml" to (+ "<x xmlns:a=\"$aNs\"><a:p><a:r><a:t>smart</a:t></a:r></a:p></x>"))+ assertTrue(frames(doc)[0].frame.paragraphs.any { it.spans.any { s -> s.text == "smart" } })+ }++ // ---- Drawing text: bullets, numbering, links, caps ----++ @Test fun bulletsAndNumbering() {+ // Slide text with bullets/numbering round-trips through the exporter, which emits+ // real txBody parts; parseTxBody covers the read path (see OoxmlDirectSliceTest).+ val doc = com.vayunmathur.library.ui.odf.OdfDocument.Presentation(+ title = "b",+ slides = listOf(com.vayunmathur.library.ui.odf.OdfSlide(+ name = "S1",+ elements = listOf(com.vayunmathur.library.ui.odf.OdfSlideElement.Frame(+ com.vayunmathur.library.ui.odf.OdfFrame(+ 36f, 36f, 640f, 200f,+ listOf(+ com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan("bullet")),+ style = com.vayunmathur.library.ui.odf.ParagraphStyle.LIST_ITEM,+ listType = ListType.BULLET,+ listBulletChar = "-"),+ com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan("one")),+ style = com.vayunmathur.library.ui.odf.ParagraphStyle.LIST_ITEM,+ listType = ListType.NUMBERED,+ listLevel = 1,+ listNumberFormat = "a"),+ com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan("two")),+ style = com.vayunmathur.library.ui.odf.ParagraphStyle.LIST_ITEM,+ listType = ListType.NUMBERED,+ listLevel = 1,+ listNumberFormat = "I"))))))))+ val back = OoxmlImporter.import(+ com.vayunmathur.library.ui.odf.OoxmlExporter.export(doc), "b.pptx")+ as com.vayunmathur.library.ui.odf.OdfDocument.Presentation+ val ps = back.slides[0].elements+ .filterIsInstance<com.vayunmathur.library.ui.odf.OdfSlideElement.Frame>()[0]+ .frame.paragraphs+ assertEquals(ListType.BULLET, ps[0].listType)+ assertEquals("-", ps[0].listBulletChar)+ assertEquals(ListType.NUMBERED, ps[1].listType)+ assertEquals("a", ps[1].listNumberFormat)+ assertEquals(1, ps[1].listItemIndex)+ assertEquals(2, ps[2].listItemIndex)+ assertEquals("I", ps[2].listNumberFormat)+ }++ @Test fun runLinksColorsCapsSpacing() {+ // Rich drawing-run formatting round-trips through the exporter; the read path+ // (rPr emphasis/metrics/color/font/link) is covered directly in OoxmlDirectSliceTest.+ val doc = com.vayunmathur.library.ui.odf.OdfDocument.Presentation(+ title = "r",+ slides = listOf(com.vayunmathur.library.ui.odf.OdfSlide(+ name = "S1",+ elements = listOf(com.vayunmathur.library.ui.odf.OdfSlideElement.Frame(+ com.vayunmathur.library.ui.odf.OdfFrame(+ 36f, 36f, 640f, 200f,+ listOf(com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan(+ "rich",+ bold = true,+ italic = true,+ underline = true,+ strikethrough = true,+ fontSize = 12f,+ fontFamily = "Verdana",+ color = 0xFF00FF00,+ href = "https://r.test",+ textTransform = "uppercase"))))))))))+ val back = OoxmlImporter.import(+ com.vayunmathur.library.ui.odf.OoxmlExporter.export(doc), "r.pptx")+ as com.vayunmathur.library.ui.odf.OdfDocument.Presentation+ val rich = back.slides[0].elements+ .filterIsInstance<com.vayunmathur.library.ui.odf.OdfSlideElement.Frame>()[0]+ .frame.paragraphs[0].spans.first { it.text == "rich" }+ assertTrue(rich.bold && rich.italic && rich.underline && rich.strikethrough)+ assertEquals(0xFF00FF00L, rich.color)+ assertEquals("Verdana", rich.fontFamily)+ // NOTE: a:hlinkClick carries no r:id through the exporter (export writes a bare+ // hlinkClick with no relationship), so href does not round-trip; the read path for+ // run hyperlinks is covered directly in OoxmlDirectSliceTest.pptxDirectRichRun.+ // NOTE: textTransform="uppercase" does not round-trip either: pptxRun() never writes+ // cap="all" on a:rPr, so the reader (which maps cap all/small -> uppercase) sees+ // nothing. The read path is covered directly in OoxmlDirectSliceTest.pptxDirectCapsRun.+ assertEquals(12f, rich.fontSize!!, 0.01f)+ }++ @Test fun emptyParagraphDropped() {+ // Empty paragraphs are dropped on read (see pptxDirectEmptyPara); an exporter-built+ // slide keeps its real paragraphs.+ val doc = com.vayunmathur.library.ui.odf.OdfDocument.Presentation(+ title = "e",+ slides = listOf(com.vayunmathur.library.ui.odf.OdfSlide(+ name = "S1",+ elements = listOf(com.vayunmathur.library.ui.odf.OdfSlideElement.Frame(+ com.vayunmathur.library.ui.odf.OdfFrame(+ 36f, 36f, 640f, 200f,+ listOf(com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan("real"))))))))))+ val back = OoxmlImporter.import(+ com.vayunmathur.library.ui.odf.OoxmlExporter.export(doc), "e.pptx")+ as com.vayunmathur.library.ui.odf.OdfDocument.Presentation+ val paras = back.slides[0].elements+ .filterIsInstance<com.vayunmathur.library.ui.odf.OdfSlideElement.Frame>()[0]+ .frame.paragraphs+ assertEquals(1, paras.size)+ assertEquals("real", paras[0].spans[0].text)+ }++ // ---- Background / transition / notes / placeholders ----++ @Test fun backgroundColorAndImage() {+ val png = byteArrayOf(4, 5)+ val bos = java.io.ByteArrayOutputStream()+ java.util.zip.ZipOutputStream(bos).use { zos ->+ fun add(n: String, c: ByteArray) {+ zos.putNextEntry(java.util.zip.ZipEntry(n)); zos.write(c); zos.closeEntry()+ }+ add("ppt/slides/slide1.xml", (+ "<p:sld xmlns:p=\"p\" xmlns:a=\"a\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<p:cSld><p:bg><p:bgPr><a:solidFill><a:srgbClr val=\"112233\"/></a:solidFill>" ++ "<a:blip r:embed=\"bg1\"/></p:bgPr></p:bg><p:spTree/></p:cSld></p:sld>").toByteArray())+ add("ppt/slides/_rels/slide1.xml.rels", ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"bg1\" Type=\"http://t/image\" Target=\"../media/bg.png\"/></Relationships>").toByteArray())+ add("ppt/media/bg.png", png)+ }+ val doc = OoxmlImporter.import(bos.toByteArray(), "bg.pptx") as OdfDocument.Presentation+ assertEquals(0xFF112233L, doc.slides[0].backgroundColor)+ assertEquals("media/bg.png", doc.slides[0].backgroundImagePath)+ }++ @Test fun transitionMaps() {+ val doc = pptx("ppt/slides/slide1.xml" to (+ "<p:sld xmlns:p=\"p\"><p:cSld><p:spTree/></p:cSld>" ++ "<p:transition spd=\"med\"><p:fade/></p:transition></p:sld>"))+ assertEquals("fade", doc.slides[0].transitionType)+ assertEquals("medium", doc.slides[0].transitionSpeed)+ val wipe = pptx("ppt/slides/slide1.xml" to (+ "<p:sld xmlns:p=\"p\"><p:cSld><p:spTree/></p:cSld>" ++ "<p:transition spd=\"slow\"><p:wipe/></p:transition></p:sld>"))+ assertEquals("wipe", wipe.slides[0].transitionType)+ assertEquals("slow", wipe.slides[0].transitionSpeed)+ val unknown = pptx("ppt/slides/slide1.xml" to (+ "<p:sld xmlns:p=\"p\"><p:cSld><p:spTree/></p:cSld>" ++ "<p:transition><p:spin/></p:transition></p:sld>"))+ assertNull(unknown.slides[0].transitionType)+ }++ @Test fun notesSlideText() {+ // Notes slides round-trip through the exporter; parseNotes covers the read path.+ val doc = com.vayunmathur.library.ui.odf.OdfDocument.Presentation(+ title = "n",+ slides = listOf(com.vayunmathur.library.ui.odf.OdfSlide(+ name = "S1",+ notes = listOf(com.vayunmathur.library.ui.odf.OdfParagraph(+ listOf(com.vayunmathur.library.ui.odf.OdfSpan("remember this")))))))+ val back = OoxmlImporter.import(+ com.vayunmathur.library.ui.odf.OoxmlExporter.export(doc), "n.pptx")+ as com.vayunmathur.library.ui.odf.OdfDocument.Presentation+ assertTrue(back.slides[0].notes.any { it.spans.any { s -> s.text == "remember this" } })+ }++ @Test fun placeholderInheritsLayoutGeometry() {+ val doc = pptx(+ "ppt/slides/slide1.xml" to slide(+ "<p:sp><p:nvSpPr><p:nvPr><p:ph type=\"title\"/></p:nvPr></p:nvSpPr>" ++ "<p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/><a:bodyPr xmlns:a=\"a\"/><a:p xmlns:a=\"a\"><a:r><a:t>laid out</a:t></a:r></a:p></p:txBody></p:sp>"),+ "ppt/slides/_rels/slide1.xml.rels" to (+ "<Relationships xmlns=\"p\"><Relationship Id=\"l1\" Type=\"http://t/slideLayout\" Target=\"../layouts/l1.xml\"/></Relationships>"),+ "ppt/layouts/l1.xml" to (+ "<p:layout xmlns:p=\"p\" xmlns:a=\"a\"><p:cSld><p:spTree>" ++ "<p:sp><p:nvSpPr><p:nvPr><p:ph type=\"title\"/></p:nvPr></p:nvSpPr>" ++ "<p:spPr><a:xfrm><a:off x=\"457200\" y=\"457200\"/>" ++ "<a:ext cx=\"3657600\" cy=\"914400\"/></a:xfrm></p:spPr></p:sp>" ++ "</p:spTree></p:cSld></p:layout>"))+ val frame = frames(doc)[0].frame+ assertEquals(48f, frame.x, 0.5f)+ assertEquals(384f, frame.width, 0.5f)+ }++ @Test fun clrMapAndPlaceholderMapHelpers() {+ val m = OoxmlPptxPlaceholders.parseClrMap(+ "<master><clrMap bg1=\"lt1\" tx1=\"dk1\" accent1=\"accent2\"/></master>")+ assertEquals("lt1", m["bg1"])+ assertEquals("accent2", m["accent1"])+ assertTrue(OoxmlPptxPlaceholders.parseClrMap(null).isEmpty())+ assertTrue(OoxmlPptxPlaceholders.parseClrMap("<master/>").isEmpty())+ assertTrue(OoxmlPptxPlaceholders.parsePlaceholderGeoms(+ OoxmlPackage(emptyMap(), emptyMap()), null).isEmpty())+ }++ @Test fun placeholderMapMatchSemantics() {+ // idx beats type; ctrTitle normalizes to title; null type means body; master is+ // the fallback when layout misses.+ fun P(type: String?, idx: String?, x: Float, y: Float, w: Float, h: Float) =+ OoxmlPptxPlaceholders.PlaceholderInfo(type, idx, x, y, w, h)+ val map = OoxmlPptxPlaceholders.PlaceholderMap(+ layout = listOf(P("title", "7", 1f, 2f, 3f, 4f), P("body", null, 5f, 6f, 7f, 8f)),+ master = listOf(P("title", null, 10f, 20f, 30f, 40f)))+ assertEquals(listOf(1f, 2f, 3f, 4f), map.geom("title", "7")!!.toList())+ assertEquals(listOf(5f, 6f, 7f, 8f), map.geom(null, null)!!.toList())+ assertEquals(listOf(1f, 2f, 3f, 4f), map.geom("ctrTitle", null)!!.toList())+ // idx match is tried only against the SAME list's entries: "9" matches nothing in+ // layout, so type matching falls back to layout's title before master's.+ assertEquals(listOf(1f, 2f, 3f, 4f), map.geom("title", "9")!!.toList())+ // Master fallback: a type missing from layout resolves from master.+ val masterFallback = OoxmlPptxPlaceholders.PlaceholderMap(+ layout = listOf(P("body", null, 5f, 6f, 7f, 8f)),+ master = listOf(P("title", null, 10f, 20f, 30f, 40f)))+ assertEquals(listOf(10f, 20f, 30f, 40f), masterFallback.geom("title", null)!!.toList())+ assertNull(map.geom("pic", "99"))+ assertNull(OoxmlPptxPlaceholders.PlaceholderMap(emptyList(), emptyList()).geom("title", null))+ }++ @Test fun shapeWithoutXfrmStacksBelow() {+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:sp><p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/><a:bodyPr xmlns:a=\"a\"/>" ++ "<a:p xmlns:a=\"a\"><a:r><a:t>auto</a:t></a:r></a:p></p:txBody></p:sp>"))+ val frame = frames(doc)[0].frame+ assertEquals(36f, frame.x, 0.01f)+ assertEquals(640f, frame.width, 0.01f)+ }++ @Test fun emptyTextBodyYieldsPlaceholderParagraph() {+ // A shape with no txBody paragraphs still yields one (empty) paragraph frame+ // (covers textFrame's ifEmpty fallback plus the min-height clamp).+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:sp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"100\"/></a:xfrm>" ++ "<a:prstGeom prst=\"rect\"/></p:spPr>" ++ "<p:txBody><a:bodyPr wrap=\"square\"/><a:lstStyle/></p:txBody></p:sp>"))+ val frame = frames(doc)[0].frame+ assertEquals(1, frame.paragraphs.size)+ assertEquals("", frame.paragraphs[0].spans[0].text)+ }++ @Test fun shapeGeometriesMap() {+ // shapeFor geometry branches: ellipse/circle, roundRect, custom fallback.+ val doc = pptx("ppt/slides/slide1.xml" to slide(+ "<p:sp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"ellipse\"/></p:spPr></p:sp>",+ "<p:sp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"roundRect\"/></p:spPr></p:sp>",+ "<p:sp><p:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/>" ++ "<a:ext cx=\"914400\" cy=\"914400\"/></a:xfrm>" ++ "<a:prstGeom prst=\"star5\"/></p:spPr></p:sp>"))+ val shapes = doc.slides[0].elements+ .filterIsInstance<OdfSlideElement.Shape>().map { it.shape }+ assertEquals(3, shapes.size)+ assertTrue(shapes[0] is OdfShape.Ellipse)+ assertTrue(shapes[1] is OdfShape.Rect)+ assertTrue(shapes[2] is OdfShape.CustomShape)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlThemeColorSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlThemeColorSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlThemeColorSliceTest.ktnew file mode 100644index 0000000000..81b2a08887--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlThemeColorSliceTest.kt@@ -0,0 +1,257 @@+package com.vayunmathur.office.odf++import org.xmlpull.v1.XmlPullParser+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): tests for theme resolution ([OoxmlTheme]), DrawingML color elements+ * ([OoxmlColor]), document properties ([OoxmlMetadata]) and SmartArt text fallback+ * ([OoxmlDiagram]).+ */+class OoxmlThemeColorSliceTest {++ private fun atTag(xml: String, tag: String): XmlPullParser {+ val p = OoxmlXml.newParser(xml)+ var e = p.eventType+ while (!(e == XmlPullParser.START_TAG && p.name == tag)) {+ e = p.next()+ if (e == XmlPullParser.END_DOCUMENT) throw IllegalArgumentException("no <$tag> in $xml")+ }+ return p+ }++ // ---- OoxmlTheme ----++ @Test fun themeDefaults() {+ val d = OoxmlTheme.DEFAULT+ assertEquals(0xFF4472C4L, d.schemeColor("accent1"))+ assertEquals("Calibri Light", d.majorFont)+ assertEquals("Calibri", d.minorFont)+ // tx/bg aliases fall back to the standard mapping.+ assertEquals(d.colors["dk1"], d.schemeColor("tx1"))+ assertEquals(d.colors["lt1"], d.schemeColor("bg1"))+ assertEquals(d.colors["dk2"], d.schemeColor("tx2"))+ assertEquals(d.colors["lt2"], d.schemeColor("bg2"))+ assertNull(d.schemeColor("phClr"))+ assertNull(d.schemeColor(null))+ assertNull(d.schemeColor("nope"))+ }++ @Test fun themeParseNullGivesDefault() {+ assertTrue(OoxmlTheme.parse(null) === OoxmlTheme.DEFAULT)+ }++ @Test fun themeParseFillsMissingSlots() {+ val theme = OoxmlTheme.parse(+ "<theme><themeElements><clrScheme name=\"X\">" ++ "<accent1><srgbClr val=\"123456\"/></accent1></clrScheme>" ++ "<fontScheme><majorFont><latin typeface=\"Arial\"/></majorFont>" ++ "<minorFont><latin typeface=\"Times\"/></minorFont></fontScheme>" ++ "</themeElements></theme>")+ assertEquals(0xFF123456L, theme.schemeColor("accent1"))+ assertEquals("Arial", theme.majorFont)+ assertEquals("Times", theme.minorFont)+ // Missing slots fall back to DEFAULT so lookups never return null unexpectedly.+ assertEquals(OoxmlTheme.DEFAULT.schemeColor("accent2"), theme.schemeColor("accent2"))+ }++ @Test fun themeParseSysClrSlot() {+ val theme = OoxmlTheme.parse(+ "<theme><themeElements><clrScheme name=\"X\">" ++ "<dk1><sysClr val=\"windowText\" lastClr=\"010203\"/></dk1>" ++ "<lt1><sysClr val=\"window\"/></lt1>" ++ "</clrScheme></themeElements></theme>")+ assertEquals(0xFF010203L, theme.schemeColor("dk1"))+ assertEquals(0xFFFFFFFFL, theme.schemeColor("lt1"))+ }++ @Test fun themeWithClrMapOverridesAliases() {+ val mapped = OoxmlTheme.DEFAULT.withClrMap(mapOf("tx1" to "lt1", "bg1" to "dk1"))+ assertEquals(OoxmlTheme.DEFAULT.colors["lt1"], mapped.schemeColor("tx1"))+ assertEquals(OoxmlTheme.DEFAULT.colors["dk1"], mapped.schemeColor("bg1"))+ // Empty map returns the same instance.+ assertTrue(OoxmlTheme.DEFAULT.withClrMap(emptyMap()) === OoxmlTheme.DEFAULT)+ }++ // ---- OoxmlColor ----++ @Test fun colorSrgb() {+ val c = OoxmlColor.parse(atTag("<root><srgbClr val=\"FF0000\"/></root>", "srgbClr"), OoxmlTheme.DEFAULT)+ assertEquals(0xFFFF0000L, c)+ }++ @Test fun colorSrgbWithShadeTransform() {+ val c = OoxmlColor.parse(+ atTag("<root><srgbClr val=\"FFFFFF\"><shade val=\"50000\"/></srgbClr></root>", "srgbClr"),+ OoxmlTheme.DEFAULT)+ assertEquals(127, (((c ?: 0L) ushr 16) and 0xFF).toInt())+ }++ @Test fun colorSysClrPrefersLastClr() {+ val c = OoxmlColor.parse(+ atTag("<root><sysClr val=\"windowText\" lastClr=\"112233\"/></root>", "sysClr"),+ OoxmlTheme.DEFAULT)+ assertEquals(0xFF112233L, c)+ // Without lastClr, falls back to the system color name.+ val c2 = OoxmlColor.parse(+ atTag("<root><sysClr val=\"window\"/></root>", "sysClr"),+ OoxmlTheme.DEFAULT)+ assertEquals(0xFFFFFFFFL, c2)+ }++ @Test fun colorSchemeClr() {+ val c = OoxmlColor.parse(+ atTag("<root><schemeClr val=\"accent1\"/></root>", "schemeClr"),+ OoxmlTheme.DEFAULT)+ assertEquals(0xFF4472C4L, c)+ assertNull(OoxmlColor.parse(+ atTag("<root><schemeClr val=\"phClr\"/></root>", "schemeClr"),+ OoxmlTheme.DEFAULT))+ }++ @Test fun colorPresetAndScrgb() {+ assertEquals(+ 0xFFFF0000L,+ OoxmlColor.parse(atTag("<root><prstClr val=\"red\"/></root>", "prstClr"), OoxmlTheme.DEFAULT))+ assertNull(OoxmlColor.parse(+ atTag("<root><prstClr val=\"plaid\"/></root>", "prstClr"),+ OoxmlTheme.DEFAULT))+ assertEquals(+ 0xFFFF0000L,+ OoxmlColor.parse(+ atTag("<root><scrgbClr r=\"100000\" g=\"0\" b=\"0\"/></root>", "scrgbClr"),+ OoxmlTheme.DEFAULT))+ assertNull(OoxmlColor.parse(+ atTag("<root><scrgbClr r=\"100000\" g=\"oops\"/></root>", "scrgbClr"),+ OoxmlTheme.DEFAULT))+ }++ @Test fun colorUnknownTagIsNull() {+ // Bare context color / unknown element: no resolvable base.+ assertNull(OoxmlColor.parse(+ atTag("<root><phClr/></root>", "phClr"),+ OoxmlTheme.DEFAULT))+ }++ @Test fun colorLumModTransform() {+ val c = OoxmlColor.parse(+ atTag("<root><srgbClr val=\"FF0000\"><lumMod val=\"50000\"/></srgbClr></root>", "srgbClr"),+ OoxmlTheme.DEFAULT)+ val r = (((c ?: 0L) ushr 16) and 0xFF).toInt()+ assertTrue(r in 120..140, "halved red channel was $r")+ }++ @Test fun colorSatModAndAlphaAndLumOff() {+ val grey = OoxmlColor.parse(+ atTag("<root><srgbClr val=\"FF0000\"><satMod val=\"0\"/></srgbClr></root>", "srgbClr"),+ OoxmlTheme.DEFAULT) ?: 0L+ assertEquals((grey ushr 16) and 0xFF, (grey ushr 8) and 0xFF)+ assertEquals((grey ushr 8) and 0xFF, grey and 0xFF)+ val half = OoxmlColor.parse(+ atTag("<root><srgbClr val=\"FF0000\"><alpha val=\"50000\"/></srgbClr></root>", "srgbClr"),+ OoxmlTheme.DEFAULT) ?: 0L+ assertEquals(127, ((half ushr 24) and 0xFF).toInt())+ val lifted = OoxmlColor.parse(+ atTag("<root><srgbClr val=\"000000\"><lumOff val=\"50000\"/></srgbClr></root>", "srgbClr"),+ OoxmlTheme.DEFAULT) ?: 0L+ assertTrue((((lifted ushr 16) and 0xFF).toInt()) > 100)+ }++ // ---- OoxmlMetadata ----++ private fun metaPkg() = OoxmlPackage(+ mapOf(+ "docProps/core.xml" to (+ "<coreProperties xmlns:dc=\"d\">" ++ "<title>My Doc</title><creator>Ada</creator><subject>S</subject>" ++ "<description>D</description><keywords>a, b;c </keywords>" ++ "<created>2024-01-02T03:04:05Z</created><modified>2024-02-03T00:00:00Z</modified>" ++ "</coreProperties>"),+ "docProps/app.xml" to (+ "<Properties><Application>Word</Application><Company>Acme</Company>" ++ "<Words>10</Words><Characters>60</Characters><Pages>2</Pages>" ++ "<Paragraphs>3</Paragraphs><TotalTime>7</TotalTime></Properties>"),+ "docProps/custom.xml" to (+ "<Properties><property name=\"Owner\"><lpwstr>Bo</lpwstr></property>" ++ "<property name=\"Count\"><i4>42</i4></property>" ++ "<property name=\"Flag\"><bool>true</bool></property>" ++ "<property name=\"When\"><filetime>2024-01-01</filetime></property>" ++ "</Properties>")+ ),+ emptyMap())++ @Test fun metadataParsesAllParts() {+ val m = OoxmlMetadata.parse(metaPkg())+ assertEquals("My Doc", m.title)+ assertEquals("Ada", m.creator)+ assertEquals("Ada", m.author)+ assertEquals("S", m.subject)+ assertEquals("D", m.description)+ assertEquals(listOf("a", "b", "c"), m.keywords)+ assertEquals("2024-01-02T03:04:05Z", m.creationDate)+ assertEquals("2024-02-03T00:00:00Z", m.modifiedDate)+ assertEquals("Word", m.generator)+ assertEquals(10, m.wordCount)+ assertEquals(60, m.charCount)+ assertEquals(2, m.pageCount)+ assertEquals(3, m.paragraphCount)+ assertEquals(7, m.editingCycles)+ assertEquals("Bo", m.userDefined["Owner"])+ assertEquals("Acme", m.userDefined["Company"])+ assertEquals("string", m.userDefinedTypes["Owner"])+ assertEquals("float", m.userDefinedTypes["Count"])+ assertEquals("boolean", m.userDefinedTypes["Flag"])+ assertEquals("date", m.userDefinedTypes["When"])+ }++ @Test fun metadataEmptyPackageGivesDefaults() {+ val m = OoxmlMetadata.parse(OoxmlPackage(emptyMap(), emptyMap()))+ assertNull(m.title)+ assertNull(m.creator)+ assertTrue(m.keywords.isEmpty())+ assertNull(m.wordCount)+ assertTrue(m.userDefined.isEmpty())+ }++ @Test fun metadataIgnoresBlankAndBadNumbers() {+ val m = OoxmlMetadata.parse(OoxmlPackage(+ mapOf(+ "docProps/core.xml" to "<coreProperties><title> </title><keywords></keywords></coreProperties>",+ "docProps/app.xml" to "<Properties><Words>many</Words><Pages></Pages></Properties>"),+ emptyMap()))+ assertNull(m.title)+ assertTrue(m.keywords.isEmpty())+ assertNull(m.wordCount)+ assertNull(m.pageCount)+ }++ // ---- OoxmlDiagram ----++ private val diagramNs = "http://schemas.openxmlformats.org/drawingml/2006/main"++ @Test fun diagramExtractsParagraphText() {+ val pkg = OoxmlPackage(+ mapOf("diagrams/data1.xml" to (+ "<x xmlns:a=\"$diagramNs\"><a:p><a:r><a:t>hello </a:t></a:r>" ++ "<a:r><a:t>world</a:t></a:r></a:p><a:p><a:t>second</a:t></a:p>" ++ "<a:p></a:p></x>")),+ emptyMap())+ assertEquals(listOf("hello world", "second"), OoxmlDiagram.extractText(pkg, "diagrams/data1.xml"))+ }++ @Test fun diagramMissingPartGivesEmpty() {+ val pkg = OoxmlPackage(emptyMap(), emptyMap())+ assertTrue(OoxmlDiagram.extractText(pkg, "diagrams/data1.xml").isEmpty())+ assertTrue(OoxmlDiagram.extractText(pkg, null).isEmpty())+ }++ @Test fun diagramIgnoresOtherNamespaces() {+ val pkg = OoxmlPackage(+ mapOf("diagrams/data1.xml" to "<x><p><t>nope</t></p></x>"),+ emptyMap())+ assertTrue(OoxmlDiagram.extractText(pkg, "diagrams/data1.xml").isEmpty())+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlUnitsSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlUnitsSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlUnitsSliceTest.ktnew file mode 100644index 0000000000..c53306139c--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlUnitsSliceTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.office.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): unit tests for the pure helpers — [OoxmlUnits] conversions/color math and+ * [OoxmlXml] parsing primitives. These underpin every docx/xlsx/pptx importer.+ */+class OoxmlUnitsSliceTest {++ // ---- Length conversions ----++ @Test fun emuToPxAndPt() {+ assertEquals(1f, OoxmlUnits.emuToPx(9525), 0.001f)+ assertEquals(2f, OoxmlUnits.emuToPx(19_050), 0.001f)+ assertEquals(0f, OoxmlUnits.emuToPx(0), 0.001f)+ assertEquals(1f, OoxmlUnits.emuToPt(12_700), 0.001f)+ }++ @Test fun twipsConversions() {+ assertEquals(1f, OoxmlUnits.twipsToPt(20), 0.001f)+ assertEquals(12f, OoxmlUnits.twipsToPt(240), 0.001f)+ // 1440 twips = 1 inch = 96 px.+ assertEquals(96f, OoxmlUnits.twipsToPx(1440), 0.01f)+ assertEquals(12f, OoxmlUnits.halfPtToPt(24), 0.001f)+ assertEquals(12f, OoxmlUnits.hundredthPtToPt(1200), 0.001f)+ }++ @Test fun angleAndExcelSizes() {+ assertEquals(90f, OoxmlUnits.angle60000ToDeg(5_400_000), 0.001f)+ assertEquals(0f, OoxmlUnits.angle60000ToDeg(0), 0.001f)+ // 8.43 default Excel column width ~= 64px.+ assertEquals(64.01f, OoxmlUnits.excelColWidthToPx(8.43f), 0.05f)+ assertEquals(16f, OoxmlUnits.ptToPx(12f), 0.001f)+ }++ // ---- Hex colors ----++ @Test fun hexColorForms() {+ assertEquals(0xFFFF0000L, OoxmlUnits.hexColor("#FF0000"))+ assertEquals(0xFF00FF00L, OoxmlUnits.hexColor("00FF00"))+ assertEquals(0x800000FFL, OoxmlUnits.hexColor("800000FF"))+ assertNull(OoxmlUnits.hexColor(null))+ assertNull(OoxmlUnits.hexColor(""))+ assertNull(OoxmlUnits.hexColor("auto"))+ assertNull(OoxmlUnits.hexColor("AUTO"))+ assertNull(OoxmlUnits.hexColor("xyz"))+ assertNull(OoxmlUnits.hexColor("12345"))+ assertNull(OoxmlUnits.hexColor("red"))+ }++ @Test fun highlightColors() {+ assertEquals(0xFFFFFF00L, OoxmlUnits.highlightColor("yellow"))+ assertEquals(0xFFFF0000L, OoxmlUnits.highlightColor("RED"))+ assertEquals(0xFFA9A9A9L, OoxmlUnits.highlightColor("darkGray"))+ assertNull(OoxmlUnits.highlightColor(null))+ assertNull(OoxmlUnits.highlightColor("chartreuse"))+ }++ @Test fun sysColors() {+ assertEquals(0xFF000000L, OoxmlUnits.sysColor("windowText"))+ assertEquals(0xFFFFFFFFL, OoxmlUnits.sysColor("window"))+ assertEquals(0xFF3399FFL, OoxmlUnits.sysColor("highlight"))+ assertNull(OoxmlUnits.sysColor("notacolor"))+ assertNull(OoxmlUnits.sysColor(null))+ }++ // ---- Color transforms ----++ @Test fun shadeAndTint() {+ // 50% shade of white -> mid-grey.+ val shaded = OoxmlUnits.applyTransforms(0xFFFFFFFF, shade = 50000)+ assertEquals(127, ((shaded ushr 16) and 0xFF).toInt())+ // Tint mixes toward white: 50% tint of black -> mid-grey.+ val tinted = OoxmlUnits.applyTransforms(0xFF000000, tint = 50000)+ assertEquals(127, ((tinted ushr 16) and 0xFF).toInt())+ // Full keep-factor (100000) -> identity.+ assertEquals(0xFF000000L, OoxmlUnits.applyTransforms(0xFF000000, tint = 100000))+ // No transforms -> identity.+ assertEquals(0xFF123456L, OoxmlUnits.applyTransforms(0xFF123456))+ }++ @Test fun lumAndSatMods() {+ // Halving luminance of pure red darkens it.+ val dark = OoxmlUnits.applyTransforms(0xFFFF0000, lumMod = 50000)+ val r = ((dark ushr 16) and 0xFF).toInt()+ assertTrue(r in 120..140, "red channel $r should roughly halve")+ // Zero saturation turns red grey.+ val grey = OoxmlUnits.applyTransforms(0xFFFF0000, satMod = 0)+ val gr = ((grey ushr 16) and 0xFF).toInt()+ val gg = ((grey ushr 8) and 0xFF).toInt()+ val gb = (grey and 0xFF).toInt()+ assertEquals(gr, gg)+ assertEquals(gg, gb)+ // Luminance offset pushes black toward grey.+ val lifted = OoxmlUnits.applyTransforms(0xFF000000, lumOff = 50000)+ assertTrue(((lifted ushr 16) and 0xFF).toInt() > 100)+ }++ @Test fun alphaTransform() {+ val half = OoxmlUnits.applyTransforms(0xFFFF0000, alpha = 50000)+ assertEquals(127, ((half ushr 24) and 0xFF).toInt())+ // Alpha clamps at both ends.+ assertEquals(0, ((OoxmlUnits.applyTransforms(0xFFFF0000, alpha = -1000) ushr 24) and 0xFF).toInt())+ assertEquals(255, ((OoxmlUnits.applyTransforms(0xFFFF0000, alpha = 200000) ushr 24) and 0xFF).toInt())+ }++ // ---- OoxmlXml primitives ----++ @Test fun newParserAndAttr() {+ val p = OoxmlXml.newParser("<a:x xmlns:a=\"u\" b:c=\"1\" d=\"2\" xmlns:b=\"v\"/>")+ var e = p.eventType+ while (e != org.xmlpull.v1.XmlPullParser.START_TAG) e = p.next()+ assertEquals("1", OoxmlXml.attr(p, "c"))+ assertEquals("2", OoxmlXml.attr(p, "d"))+ assertNull(OoxmlXml.attr(p, "missing"))+ }++ @Test fun attrNsDisambiguates() {+ // Same local name "id" in two namespaces: attrNs picks by namespace URI.+ val q = OoxmlXml.newParser("<root xmlns:r=\"urn:r\" xmlns:w=\"urn:w\"><e r:id=\"R\" w:id=\"W\"/></root>")+ var e = q.eventType+ while (!(e == org.xmlpull.v1.XmlPullParser.START_TAG && q.name == "e")) e = q.next()+ assertEquals("R", OoxmlXml.attrNs(q, "urn:r", "id"))+ assertEquals("W", OoxmlXml.attrNs(q, "urn:w", "id"))+ assertNull(OoxmlXml.attrNs(q, "urn:other", "id"))+ }++ @Test fun boolAttrSemantics() {+ assertTrue(OoxmlXml.boolAttr(null))+ assertTrue(OoxmlXml.boolAttr("1"))+ assertTrue(OoxmlXml.boolAttr("true"))+ assertTrue(OoxmlXml.boolAttr("on"))+ assertTrue(!OoxmlXml.boolAttr("0"))+ assertTrue(!OoxmlXml.boolAttr("false"))+ assertTrue(!OoxmlXml.boolAttr("off"))+ }++ @Test fun cellRefIndices() {+ assertEquals(0, OoxmlXml.colIndex("A1"))+ assertEquals(25, OoxmlXml.colIndex("Z1"))+ assertEquals(26, OoxmlXml.colIndex("AA1"))+ assertEquals(27, OoxmlXml.colIndex("AB12"))+ assertEquals(0, OoxmlXml.rowIndex("A1"))+ assertEquals(11, OoxmlXml.rowIndex("AB12"))+ assertEquals(-1, OoxmlXml.rowIndex("ABC"))+ }++ @Test fun readElementTextConcatenates() {+ val p = OoxmlXml.newParser("<r><t>Hello</t><t> world</t></r>")+ var e = p.eventType+ while (!(e == org.xmlpull.v1.XmlPullParser.START_TAG && p.name == "r")) e = p.next()+ // readElementText only stops at the matching end tag at the same depth.+ val sb = StringBuilder()+ val depth = p.depth+ var ev = p.next()+ while (!(ev == org.xmlpull.v1.XmlPullParser.END_TAG && p.depth == depth && p.name == "r")) {+ if (ev == org.xmlpull.v1.XmlPullParser.TEXT) sb.append(p.text)+ ev = p.next()+ }+ assertEquals("Hello world", sb.toString())+ }++ @Test fun skipAndForEachChild() {+ val p = OoxmlXml.newParser("<root><a>1</a><c>2</c></root>")+ var e = p.eventType+ while (!(e == org.xmlpull.v1.XmlPullParser.START_TAG && p.name == "root")) e = p.next()+ val seen = mutableListOf<String>()+ OoxmlXml.forEachChild(p, "root") { seen.add(it) }+ assertEquals(listOf("a", "c"), seen)++ val q = OoxmlXml.newParser("<root><skip><x>1<y>2</y></x></skip><keep>v</keep></root>")+ var f = q.eventType+ while (!(f == org.xmlpull.v1.XmlPullParser.START_TAG && q.name == "skip")) f = q.next()+ OoxmlXml.skipElement(q)+ // After skipping, the next start tag should be <keep>.+ var g = q.next()+ while (g != org.xmlpull.v1.XmlPullParser.START_TAG && g != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) g = q.next()+ assertEquals("keep", q.name)+ assertNotNull(q)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OoxmlXlsxSliceTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlXlsxSliceTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlXlsxSliceTest.ktnew file mode 100644index 0000000000..ccc9b4f019--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlXlsxSliceTest.kt@@ -0,0 +1,541 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 1/4 (Ooxml*): xlsx importer tests ([OoxmlXlsx], [OoxmlXlsxStyles], [OoxmlXlsxPost],+ * [OoxmlXlsxHelper]) — workbook/sheet parsing, shared strings, styles, formulas, merges,+ * hyperlinks, validations, condformats, comments, tables, drawings, dates and display strings.+ */+class OoxmlXlsxSliceTest {++ private fun xlsx(vararg entries: Pair<String, String>, name: String = "b.xlsx"): 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(), name) as OdfDocument.Spreadsheet+ }++ private fun wb(vararg sheets: String, names: String = ""): String {+ val list = sheets.mapIndexed { i, s -> "<sheet name=\"$s\" sheetId=\"${i + 1}\" r:id=\"rId${i + 1}\"/>" }+ return "<workbook xmlns=\"s\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">" ++ "<sheets>${list.joinToString("")}</sheets>" ++ "<definedNames>$names</definedNames></workbook>"+ }++ private fun wbRels(vararg targets: String): String {+ val rels = targets.mapIndexed { i, t ->+ "<Relationship Id=\"rId${i + 1}\" Type=\"http://t/worksheet\" Target=\"$t\"/>"+ }+ return "<Relationships xmlns=\"p\">${rels.joinToString("")}</Relationships>"+ }++ private val minimalWb = wb("Data")+ private val minimalRels = wbRels("worksheets/sheet1.xml")++ // ---- Values and types ----++ @Test fun stringSharedAndInline() {+ val doc = xlsx(+ "xl/workbook.xml" to minimalWb,+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/sharedStrings.xml" to "<sst xmlns=\"s\"><si><t>shared</t></si></sst>",+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\" t=\"s\"><v>0</v></c><c r=\"B1\" t=\"inlineStr\"><is><t>inline</t></is></c>" ++ "<c r=\"C1\" t=\"str\"><v>formula-text</v></c>" ++ "<c r=\"D1\" t=\"e\"><v>#DIV/0!</v></c>" ++ "<c r=\"E1\" t=\"b\"><v>1</v></c><c r=\"F1\" t=\"b\"><v>0</v></c>" ++ "</row></sheetData></worksheet>"))+ val cells = doc.sheets[0].rows[0].cells+ assertEquals("shared", cells[0].text)+ assertEquals("inline", cells[1].text)+ assertEquals("formula-text", cells[2].text)+ assertEquals("#DIV/0!", cells[3].text)+ assertEquals("TRUE", cells[4].text)+ assertEquals(1.0, cells[4].numberValue)+ assertEquals("FALSE", cells[5].text)+ }++ @Test fun phoneticRunsSkippedInSharedStrings() {+ val doc = xlsx(+ "xl/workbook.xml" to minimalWb,+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/sharedStrings.xml" to ("<sst xmlns=\"s\"><si><t>base</t>" ++ "<rPh><t>furigana</t></rPh></si></sst>"),+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\" t=\"s\"><v>0</v></c></row></sheetData></worksheet>"))+ assertEquals("base", doc.sheets[0].rows[0].cells[0].text)+ }++ @Test fun numericAndMissingValue() {+ val doc = xlsx(+ "xl/workbook.xml" to minimalWb,+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\"><v>2.5</v></c><c r=\"B1\"/>" ++ "</row></sheetData></worksheet>"))+ val cells = doc.sheets[0].rows[0].cells+ assertEquals(2.5, cells[0].numberValue!!, 0.0001)+ assertEquals("float", cells[0].valueType)+ assertEquals("", cells[1].text)+ }++ // ---- Formulas incl. shared ----++ @Test fun formulasTranslateAndSharedShift() {+ val doc = xlsx(+ "xl/workbook.xml" to minimalWb,+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData>" ++ "<row r=\"1\"><c r=\"A1\"><v>1</v></c></row>" ++ "<row r=\"2\"><c r=\"A2\"><f>SUM(A1:A1)</f><v>1</v></c></row>" ++ "<row r=\"3\"><c r=\"A3\"><f t=\"shared\" si=\"0\">SUM(A1:A2)</f><v>2</v></c></row>" ++ "<row r=\"4\"><c r=\"A4\"><f t=\"shared\" si=\"0\"/><v>3</v></c></row>" ++ "</sheetData></worksheet>"))+ val rows = doc.sheets[0].rows+ assertEquals("of:=SUM([.A1:.A1])", rows[1].cells[0].formula)+ assertEquals("of:=SUM([.A1:.A2])", rows[2].cells[0].formula)+ // Dependent shifts the master's refs down by one row.+ assertEquals("of:=SUM([.A2:.A3])", rows[3].cells[0].formula)+ }++ // ---- Styles ----++ @Test fun cellStyleBoldFillAlign() {+ val doc = xlsx(+ "xl/workbook.xml" to minimalWb,+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/styles.xml" to ("<styleSheet xmlns=\"s\">" ++ "<fonts count=\"1\"><font><b/><color rgb=\"FFFF0000\"/><i/></font></fonts>" ++ "<fills count=\"2\"><fill><patternFill patternType=\"none\"/></fill>" ++ "<fill><patternFill patternType=\"solid\"><fgColor rgb=\"FFFFFF00\"/></patternFill></fill></fills>" ++ "<borders count=\"1\"><border/></borders>" ++ "<cellXfs count=\"2\">" ++ "<xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/>" ++ "<xf numFmtId=\"0\" fontId=\"0\" fillId=\"1\" borderId=\"0\" applyFill=\"1\">" ++ "<alignment horizontal=\"center\" vertical=\"bottom\" wrapText=\"1\" textRotation=\"45\"/>" ++ "</xf></cellXfs></styleSheet>"),+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\" s=\"1\"><v>7</v></c></row></sheetData></worksheet>"))+ val cell = doc.sheets[0].rows[0].cells[0]+ assertTrue(cell.bold)+ assertEquals(0xFFFF0000L, cell.textColor)+ assertEquals(0xFFFFFF00L, cell.backgroundColor)+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, cell.alignment)+ assertEquals("bottom", cell.verticalAlign)+ assertTrue(cell.wrap)+ assertEquals(45, cell.textRotation)+ }++ @Test fun themeAndIndexedColors() {+ val styles = OoxmlXlsxStyles.parseStyles(+ "<styleSheet xmlns=\"s\"><fonts count=\"2\">" ++ "<font><color theme=\"4\" tint=\"0.5\"/></font>" ++ "<font><color indexed=\"10\"/></font></fonts>" ++ "<fills count=\"1\"><fill><patternFill patternType=\"solid\">" ++ "<fgColor indexed=\"64\"/></patternFill></fill></fills>" ++ "<cellXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellXfs>" ++ "</styleSheet>",+ OoxmlTheme.DEFAULT)+ val tinted = styles.fonts[0].color+ assertNotNull(tinted)+ // Tinted accent1 (blue) toward white: channels must rise above the base.+ assertTrue((((tinted ushr 16) and 0xFF).toInt()) >= 0x44)+ assertEquals(0xFFFF0000L, styles.fonts[1].color)+ assertEquals(0xFF000000L, styles.fills[0])+ }++ @Test fun borderWeightsAndKinds() {+ val styles = OoxmlXlsxStyles.parseStyles(+ "<styleSheet xmlns=\"s\"><borders count=\"1\"><border>" ++ "<top style=\"thin\"/><bottom style=\"mediumDashed\"/>" ++ "<left style=\"double\"/><right style=\"dotted\"/>" ++ "<diagonal style=\"none\"/></border></borders>" ++ "<cellXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellXfs>" ++ "</styleSheet>",+ OoxmlTheme.DEFAULT)+ val b = styles.borders[0]+ assertTrue(b.top!!.contains("0.50pt solid"))+ assertTrue(b.bottom!!.contains("1.50pt dashed"))+ assertTrue(b.left!!.contains("double"))+ assertTrue(b.right!!.contains("dotted"))+ }++ @Test fun numberFormatsBuiltinAndCustom() {+ val styles = OoxmlXlsxStyles.parseStyles(+ "<styleSheet xmlns=\"s\"><numFmts count=\"1\">" ++ "<numFmt numFmtId=\"200\" formatCode=\"0.00%\"/></numFmts>" ++ "<cellXfs count=\"1\"><xf numFmtId=\"200\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellXfs>" ++ "</styleSheet>",+ OoxmlTheme.DEFAULT)+ assertTrue(styles.isDateFmt(14))+ assertFalse(styles.isDateFmt(10))+ assertTrue(styles.isDateFmt(200).not())+ assertNotNull(styles.numberFormat(200))+ assertNull(styles.numberFormat(999))+ }++ // ---- Sheet layout ----++ @Test fun colsRowsPanesAndTabColor() {+ val doc = xlsx(+ "xl/workbook.xml" to minimalWb,+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\">" ++ "<sheetPr><tabColor rgb=\"FF00FF00\"/></sheetPr>" ++ "<sheetViews><sheetView><pane state=\"frozen\" xSplit=\"1\" ySplit=\"2\"/></sheetView></sheetViews>" ++ "<cols><col min=\"1\" max=\"2\" width=\"20\"/><col min=\"3\" max=\"3\" hidden=\"1\"/></cols>" ++ "<sheetData><row r=\"1\"/><row r=\"3\" ht=\"30\" hidden=\"1\"><c r=\"A3\"><v>1</v></c></row>" ++ "</sheetData></worksheet>"))+ val sheet = doc.sheets[0]+ assertEquals(2, sheet.freezeRows)+ assertEquals(1, sheet.freezeCols)+ assertEquals(0xFF00FF00L, sheet.tabColor)+ assertTrue(sheet.columnWidths[0]!! > 100f)+ assertTrue(2 in sheet.hiddenCols)+ assertTrue(2 in sheet.hiddenRows)+ assertEquals(40f, sheet.rowHeights[2]!!, 0.5f)+ }++ @Test fun hiddenSheetFlag() {+ val doc = xlsx(+ "xl/workbook.xml" to "<workbook xmlns=\"s\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><sheets>" ++ "<sheet name=\"H\" sheetId=\"1\" r:id=\"rId1\" state=\"veryHidden\"/>" ++ "<sheet name=\"V\" sheetId=\"2\" r:id=\"rId2\"/></sheets></workbook>",+ "xl/_rels/workbook.xml.rels" to wbRels("worksheets/sheet1.xml", "worksheets/sheet2.xml"),+ "xl/worksheets/sheet1.xml" to "<worksheet xmlns=\"s\"><sheetData/></worksheet>",+ "xl/worksheets/sheet2.xml" to "<worksheet xmlns=\"s\"><sheetData/></worksheet>")+ assertTrue(doc.sheets[0].hidden)+ assertFalse(doc.sheets[1].hidden)+ }++ // ---- Merges / hyperlinks / print / names ----++ @Test fun mergesHyperlinksPrintAreaAndNames() {+ val doc = xlsx(+ "xl/workbook.xml" to (wb("S", names =+ "<definedName name=\"MyRange\">S!\$A\$1:\$B\$2</definedName>" ++ "<definedName name=\"_xlnm.Print_Area\" localSheetId=\"0\">S!\$A\$1:\$C\$3</definedName>" ++ "<definedName name=\"_xlnm._Filter\">x</definedName>")),+ "xl/_rels/workbook.xml.rels" to minimalRels,+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\"><v>1</v></c><c r=\"B1\"><v>2</v></c></row></sheetData>" ++ "<mergeCells count=\"1\"><mergeCell ref=\"A1:B1\"/></mergeCells>" ++ "<hyperlinks><hyperlink ref=\"A1\" r:id=\"h1\" " ++ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" ++ "<hyperlink ref=\"B1\" location=\"Target!A9\"/></hyperlinks></worksheet>"),+ "xl/worksheets/_rels/sheet1.xml.rels" to (+ "<Relationships xmlns=\"p\"><Relationship Id=\"h1\" Type=\"http://t/hyperlink\" " ++ "Target=\"https://h.test\" TargetMode=\"External\"/></Relationships>"))+ val sheet = doc.sheets[0]+ assertEquals(2, sheet.rows[0].cells[0].spannedColumns)+ assertTrue(sheet.rows[0].cells[1].isCovered)+ assertEquals("https://h.test", sheet.rows[0].cells[0].hyperlink)+ assertEquals("#Target!A9", sheet.rows[0].cells[1].hyperlink)+ assertEquals("S.A1:S.C3", sheet.printRanges)+ assertTrue(doc.namedRanges.any { it.name == "MyRange" })+ assertFalse(doc.namedRanges.any { it.name.startsWith("_xlnm") })+ }++ // ---
Diff truncated.