office: add tests for slice 2/4 (OdfParser*)
- Commit
3ded55bba0421d59beaa6c12d87ce4843ec4020c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 18:50 UTC (29 days ago)
- Parents
0abcddf
OdfParser* slice coverage 86.3% INSTRUCTION (14385/16669) in merged report. Covers text/body/frame parsing, inline content, styles, sheets, slides, charts/meta, media (Robolectric). Bug fixes already landed separately on main. (cherry picked from commit c9b20281c6c37fc7158fab484e4e8d1a3e023824)
Diff
office/src/test/java/com/vayunmathur/office/odf/OdfParser2ChartMetaTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2ChartMetaTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2ChartMetaTest.ktnew file mode 100644index 0000000000..45d298b848--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2ChartMetaTest.kt@@ -0,0 +1,343 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.ChartType+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.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 2/4 (OdfParser*): embedded charts, metadata, page setup, header/footer+ * and number (data-style) parsing.+ */+class OdfParser2ChartMetaTest {++ private fun chartXml(+ chartClass: String = "chart:bar",+ stacked: String = "",+ legend: Boolean = true,+ titles: String = "",+ table: String? = null,+ styles: String = "",+ ): String {+ val legendTag = if (legend) "<chart:legend/>" else ""+ val data = table ?: (+ """<table:table table:name="local-table">""" ++ """<table:table-row><table:table-cell><text:p></text:p></table:table-cell>""" ++ """<table:table-cell><text:p>Q1</text:p></table:table-cell>""" ++ """<table:table-cell><text:p>Q2</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p>Apples</text:p></table:table-cell>""" ++ """<table:table-cell table:value="3"><text:p>3</text:p></table:table-cell>""" ++ """<table:table-cell><text:p>seven</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p>Pears</text:p></table:table-cell>""" ++ """<table:table-cell table:value="1"><text:p>1</text:p></table:table-cell>""" ++ """<table:table-cell table:value="2"><text:p>2</text:p></table:table-cell></table:table-row>""" ++ """</table:table>"""+ )+ // Note: no office: prefix on the root; parseChart only reads local names,+ // but the namespace-aware parser requires every used prefix to be declared.+ return """<doc xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" """ ++ """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0">""" ++ """<doc-styles>$styles</doc-styles>""" ++ """<chart:chart chart:class="$chartClass">$titles$legendTag""" ++ """<chart:plot-area $stacked><chart:series chart:style-name="s1"/><chart:series/></chart:plot-area>""" ++ data + "</chart:chart></doc>"+ }++ // --- Charts ---++ @Test+ fun bar_chart_series_categories_and_values() {+ val chart = assertNotNull(OdfParser.parseChart(chartXml()))+ assertEquals(ChartType.BAR, chart.type)+ assertEquals(listOf("Apples", "Pears"), chart.categories)+ assertEquals(2, chart.series.size)+ assertEquals("Q1", chart.series[0].name)+ assertEquals(listOf(3f, 1f), chart.series[0].values)+ // Non-numeric cached text falls back to parsed float, else 0.+ assertEquals(listOf(0f, 2f), chart.series[1].values)+ assertTrue(chart.legend)+ }++ @Test+ fun chart_type_mapping() {+ assertEquals(ChartType.LINE, OdfParser.parseChart(chartXml("chart:line"))!!.type)+ assertEquals(ChartType.SCATTER, OdfParser.parseChart(chartXml("chart:scatter"))!!.type)+ assertEquals(ChartType.PIE, OdfParser.parseChart(chartXml("chart:circle"))!!.type)+ assertEquals(ChartType.DONUT, OdfParser.parseChart(chartXml("chart:ring"))!!.type)+ assertEquals(ChartType.RADAR, OdfParser.parseChart(chartXml("chart:radar"))!!.type)+ assertEquals(ChartType.BUBBLE, OdfParser.parseChart(chartXml("chart:bubble"))!!.type)+ assertEquals(ChartType.AREA, OdfParser.parseChart(chartXml("chart:area"))!!.type)+ assertEquals(ChartType.STACKED_BAR, OdfParser.parseChart(chartXml("chart:bar", """chart:stacked="true""""))!!.type)+ assertEquals(ChartType.BAR, OdfParser.parseChart(chartXml("chart:bar", legend = false))!!.type)+ assertFalse(OdfParser.parseChart(chartXml("chart:bar", legend = false))!!.legend)+ }++ @Test+ fun chart_titles_and_axis_titles() {+ val xml = chartXml(+ titles = """<chart:title><text:p>Main</text:p></chart:title>""" ++ """<chart:axis chart:dimension="x"><chart:title><text:p>Months</text:p></chart:title></chart:axis>""" ++ """<chart:axis chart:dimension="y"><chart:title><text:p>Sales</text:p></chart:title></chart:axis>""" ++ """<chart:subtitle><text:p>Sub</text:p></chart:subtitle>"""+ )+ val chart = assertNotNull(OdfParser.parseChart(xml))+ assertEquals("Main", chart.title)+ assertEquals("Sub", chart.subtitle)+ assertEquals("Months", chart.xAxisTitle)+ assertEquals("Sales", chart.yAxisTitle)+ }++ @Test+ fun chart_series_styles_fill_and_labels() {+ val styles =+ """<style:style style:name="s1" style:family="chart">""" ++ """<style:graphic-properties draw:fill-color="#00ff00"/>""" ++ """<style:chart-properties chart:data-label-number="value"/>""" ++ """</style:style>"""+ val chart = assertNotNull(OdfParser.parseChart(chartXml(styles = styles)))+ assertEquals(0xFF00FF00L, chart.series[0].color)+ assertTrue(chart.series[0].dataLabels)+ assertFalse(chart.series[1].dataLabels)+ }++ @Test+ fun chart_rejected_without_enough_rows_or_series() {+ assertNull(OdfParser.parseChart(chartXml(table = "<table:table table:name=\"local-table\"/>")))+ val oneCol =+ """<table:table table:name="local-table">""" ++ """<table:table-row><table:table-cell><text:p>H</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p>R</text:p></table:table-cell></table:table-row>""" ++ """</table:table>"""+ assertNull(OdfParser.parseChart(chartXml(table = oneCol)))+ // Header-only (no data rows) -> null.+ val headerOnly =+ """<table:table table:name="local-table">""" ++ """<table:table-row><table:table-cell><text:p></text:p></table:table-cell>""" ++ """<table:table-cell><text:p>S</text:p></table:table-cell></table:table-row>""" ++ """</table:table>"""+ assertNull(OdfParser.parseChart(chartXml(table = headerOnly)))+ }++ @Test+ fun chart_default_series_name_when_header_blank() {+ val table =+ """<table:table table:name="local-table">""" ++ """<table:table-row><table:table-cell><text:p></text:p></table:table-cell>""" ++ """<table:table-cell><text:p></text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p>A</text:p></table:table-cell>""" ++ """<table:table-cell table:value="4"><text:p>4</text:p></table:table-cell></table:table-row>""" ++ """</table:table>"""+ assertEquals("Series 1", OdfParser.parseChart(chartXml(table = table))!!.series.single().name)+ }++ // --- Metadata ---++ private val metaHead =+ """<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" """ ++ """xmlns:dc="http://purl.org/dc/elements/1.1">""" ++ """<office:meta>"""++ private val metaTail = "</office:meta></office:document-meta>"++ @Test+ fun metadata_all_fields() {+ val m = OdfParser.parseMetadata(+ metaHead ++ """<dc:title>Report</dc:title><dc:creator>Editor</dc:creator>""" ++ """<meta:initial-creator>Author</meta:initial-creator>""" ++ """<meta:creation-date>2023-01-01</meta:creation-date><dc:date>2024-02-02</dc:date>""" ++ """<dc:description>Desc</dc:description><dc:subject>Subj</dc:subject>""" ++ """<meta:keyword>k1</meta:keyword><meta:keyword>k2</meta:keyword>""" ++ """<meta:generator>LibreOffice</meta:generator><meta:editing-cycles>7</meta:editing-cycles>""" ++ """<meta:document-statistic meta:page-count="5" meta:word-count="100" """ ++ """meta:character-count="600" meta:paragraph-count="10"/>""" ++ """<meta:user-defined meta:name="Rev" meta:value-type="float">3</meta:user-defined>""" ++ metaTail+ )+ assertEquals("Report", m.title)+ // dc:creator wins over initial-creator for author.+ assertEquals("Editor", m.author)+ assertEquals("Author", m.creator)+ assertEquals("2023-01-01", m.creationDate)+ assertEquals("2024-02-02", m.modifiedDate)+ assertEquals("Desc", m.description)+ assertEquals("Subj", m.subject)+ assertEquals(listOf("k1", "k2"), m.keywords)+ assertEquals("LibreOffice", m.generator)+ assertEquals(7, m.editingCycles)+ assertEquals(5, m.pageCount)+ assertEquals(100, m.wordCount)+ assertEquals(600, m.charCount)+ assertEquals(10, m.paragraphCount)+ assertEquals("3", m.userDefined["Rev"])+ assertEquals("float", m.userDefinedTypes["Rev"])+ }++ @Test+ fun metadata_missing_fields_default() {+ val m = OdfParser.parseMetadata(metaHead + metaTail)+ assertNull(m.title)+ assertNull(m.author)+ assertTrue(m.keywords.isEmpty())+ assertNull(m.editingCycles)+ }++ @Test+ fun metadata_initial_creator_fallback_and_bad_cycles() {+ val m = OdfParser.parseMetadata(+ metaHead + """<meta:initial-creator>Solo</meta:initial-creator>""" ++ """<meta:editing-cycles>many</meta:editing-cycles>""" + metaTail+ )+ assertEquals("Solo", m.author)+ assertNull(m.editingCycles)+ }++ // --- Page setup / header-footer ---++ private val stylesHead =+ """<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">"""++ @Test+ fun page_setup_explicit_and_uniform_margin() {+ val setup = OdfParser.parsePageSetup(+ stylesHead ++ """<style:page-layout><style:page-layout-properties fo:page-width="10cm" """ ++ """fo:page-height="20cm" fo:margin="1cm"/></style:page-layout>""" ++ """</office:document-styles>"""+ )+ assertNotNull(setup)+ assertEquals(10 * 37.8f, setup.widthPx, 0.01f)+ assertEquals(20 * 37.8f, setup.heightPx, 0.01f)+ assertEquals(37.8f, setup.marginLeftPx, 0.01f)+ assertEquals(37.8f, setup.marginTopPx, 0.01f)+ assertFalse(setup.isLandscape)+ }++ @Test+ fun page_setup_per_side_margins_and_landscape() {+ val setup = OdfParser.parsePageSetup(+ stylesHead ++ """<style:page-layout><style:page-layout-properties fo:page-width="30cm" """ ++ """fo:page-height="20cm" fo:margin-left="2cm" fo:margin-top="3cm"/></style:page-layout>""" ++ """</office:document-styles>"""+ )+ assertNotNull(setup)+ assertEquals(2 * 37.8f, setup.marginLeftPx, 0.01f)+ assertEquals(3 * 37.8f, setup.marginTopPx, 0.01f)+ // Unspecified sides fall back to defaults.+ assertEquals(com.vayunmathur.library.ui.odf.OdfPageSetup().marginRightPx, setup.marginRightPx, 0.01f)+ assertTrue(setup.isLandscape)+ }++ @Test+ fun page_setup_absent_returns_null_and_defaults_used() {+ assertNull(OdfParser.parsePageSetup(stylesHead + "</office:document-styles>"))+ }++ @Test+ fun header_footer_paragraphs_collected() {+ val hf = OdfParser.parseHeaderFooter(+ stylesHead ++ """<style:master-page><style:header><text:p>Head <text:span>one</text:span></text:p></style:header>""" ++ """<style:footer><text:p>Foot</text:p></style:footer></style:master-page>""" ++ """</office:document-styles>""",+ emptyMap()+ )+ assertEquals("Head one", hf.headerParagraphs.single().spans.joinToString("") { it.text })+ assertEquals("Foot", hf.footerParagraphs.single().spans.joinToString("") { it.text })+ }++ @Test+ fun header_footer_empty_paragraphs_skipped() {+ val hf = OdfParser.parseHeaderFooter(+ stylesHead ++ """<style:master-page><style:header><text:p></text:p></style:header></style:master-page>""" ++ """</office:document-styles>""",+ emptyMap()+ )+ assertTrue(hf.headerParagraphs.isEmpty())+ assertTrue(hf.footerParagraphs.isEmpty())+ }++ // --- Number styles ---++ private val numHead =+ """<doc xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0">"""++ @Test+ fun number_styles_all_kinds() {+ val m = OdfParser.parseNumberStyles(+ numHead ++ """<number:number-style style:name="N1">""" ++ """<number:number number:decimal-places="3" number:grouping="true"/></number:number-style>""" ++ """<number:percentage-style style:name="P1"><number:number number:decimal-places="1"/></number:percentage-style>""" ++ """<number:currency-style style:name="C1"><number:currency-symbol>€</number:currency-symbol>""" ++ """<number:number number:decimal-places="0"/></number:currency-style>""" ++ """<number:date-style style:name="D1"><number:year number:style="long"/><number:text>-</number:text>""" ++ """<number:month/><number:day/></number:date-style>""" ++ """<number:time-style style:name="T1"><number:hours/><number:minutes/></number:time-style>""" ++ """<number:number-style style:name="S1"><number:scientific-number number:decimal-places="2"/></number:number-style>""" ++ """<number:number-style style:name="F1"><number:fraction number:min-denominator-digits="2"/></number:number-style>""" ++ """</doc>"""+ )+ assertEquals(3, m["N1"]!!.decimals)+ assertTrue(m["N1"]!!.grouping)+ assertTrue(m["P1"]!!.percent)+ assertEquals("€", m["C1"]!!.currencySymbol)+ assertTrue(m["D1"]!!.isDate)+ // year + literal "-" + month + day.+ assertEquals(4, m["D1"]!!.dateTimeTokens.size)+ assertEquals("year", m["D1"]!!.dateTimeTokens[0].kind)+ assertEquals("long", m["D1"]!!.dateTimeTokens[0].style)+ assertEquals("text", m["D1"]!!.dateTimeTokens[1].kind)+ assertEquals("-", m["D1"]!!.dateTimeTokens[1].text)+ assertTrue(m["T1"]!!.isTime)+ assertTrue(m["S1"]!!.isScientific)+ assertEquals(2, m["S1"]!!.decimals)+ assertTrue(m["F1"]!!.isFraction)+ assertEquals(2, m["F1"]!!.fractionDenominatorDigits)+ }++ @Test+ fun number_styles_date_tokens_only_in_date_time() {+ val m = OdfParser.parseNumberStyles(+ numHead ++ """<number:number-style style:name="N"><number:year/><number:text>x</number:text></number:number-style>""" ++ """</doc>"""+ )+ assertTrue(m["N"]!!.dateTimeTokens.isEmpty())+ assertFalse(m["N"]!!.isDate)+ }++ // --- parseTextXml seam ---++ @Test+ fun parse_text_xml_seam_with_file_name() {+ val d = OdfParser.parseTextXml(+ """<?xml version="1.0"?><office:document """ ++ """xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">""" ++ """<office:body><office:text><text:p>seam</text:p></office:text></office:body></office:document>""",+ "custom.odt"+ )+ assertIs<OdfDocument.TextDocument>(d)+ assertEquals("custom.odt", d.title)+ val paras: List<com.vayunmathur.library.ui.odf.OdfParagraph> =+ d.content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph }+ assertEquals("seam", paras.single().spans.single().text)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2CoreTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2CoreTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2CoreTest.ktnew file mode 100644index 0000000000..0474d03435--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2CoreTest.kt@@ -0,0 +1,202 @@+package com.vayunmathur.office.odf++import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.LayoutDirection+import com.vayunmathur.library.ui.odf.OdfContentBlock+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 2/4 (OdfParser*): unit conversion, color/clip/rotation parsing and other+ * pure helpers on [OdfParser] shared by every OdfParser*.kt extension file.+ */+class OdfParser2CoreTest {++ // --- parseDimension ---++ @Test+ fun dimension_absolute_units() {+ assertEquals(2f * 37.8f, OdfParser.parseDimension("2cm"), 0.001f)+ assertEquals(5f * 3.78f, OdfParser.parseDimension("5mm"), 0.001f)+ assertEquals(96f, OdfParser.parseDimension("1in"), 0.001f)+ assertEquals(12f * 1.33f, OdfParser.parseDimension("12pt"), 0.001f)+ assertEquals(16f, OdfParser.parseDimension("1pc"), 0.001f)+ assertEquals(32f, OdfParser.parseDimension("2em"), 0.001f)+ }++ @Test+ fun dimension_unitless_and_null() {+ assertEquals(10f, OdfParser.parseDimension("10"), 0.001f)+ assertEquals(0f, OdfParser.parseDimension(null), 0.001f)+ assertEquals(0f, OdfParser.parseDimension("abc"), 0.001f)+ assertEquals(-4f, OdfParser.parseDimension("-4"), 0.001f)+ }++ // --- parseColor ---++ @Test+ fun color_six_digit_hex() {+ assertEquals(0xFFFF0000L, OdfParser.parseColor("#ff0000"))+ assertEquals(0xFF00FF00L, OdfParser.parseColor("00ff00"))+ }++ @Test+ fun color_three_digit_shorthand_expands() {+ assertEquals(0xFFFFFFFFL, OdfParser.parseColor("#FFF"))+ assertEquals(0xFF000000L, OdfParser.parseColor("#000"))+ }++ @Test+ fun color_invalid_returns_null() {+ assertNull(OdfParser.parseColor("#12"))+ assertNull(OdfParser.parseColor("red"))+ assertNull(OdfParser.parseColor(""))+ assertNull(OdfParser.parseColor("#gggggg"))+ }++ // --- parseClip ---++ @Test+ fun clip_percent_rect_returns_left_top_right_bottom() {+ val clip = assertNotNull(OdfParser.parseClip("rect(10% 20% 30% 40%)"))+ assertEquals(0.4f, clip[0], 0.0001f)+ assertEquals(0.1f, clip[1], 0.0001f)+ assertEquals(0.2f, clip[2], 0.0001f)+ assertEquals(0.3f, clip[3], 0.0001f)+ }++ @Test+ fun clip_comma_separated_and_clamped() {+ val clip = assertNotNull(OdfParser.parseClip("rect(150%, 0%, 0%, 0%)"))+ assertEquals(0.95f, clip[1], 0.0001f)+ }++ @Test+ fun clip_zero_crop_and_malformed_return_null() {+ assertNull(OdfParser.parseClip("rect(0% 0% 0% 0%)"))+ assertNull(OdfParser.parseClip(null))+ assertNull(OdfParser.parseClip("none"))+ assertNull(OdfParser.parseClip("rect(10% 20%)"))+ }++ // --- parseClipLengths ---++ @Test+ fun clip_lengths_absolute_values_become_fractions() {+ // parseDimension("10px") == 10 (unknown unit -> raw number), "40px" == 40.+ val clip = assertNotNull(OdfParser.parseClipLengths("rect(10px 20px 30px 40px)", 100f, 200f))+ assertEquals(0.4f, clip[0], 0.0001f) // left = 40/100+ assertEquals(0.05f, clip[1], 0.0001f) // top = 10/200+ assertEquals(0.2f, clip[2], 0.0001f) // right = 20/100+ assertEquals(0.15f, clip[3], 0.0001f) // bottom = 30/200+ }++ @Test+ fun clip_lengths_percent_falls_back_to_percent_parse() {+ val clip = assertNotNull(OdfParser.parseClipLengths("rect(10% 0% 0% 0%)", 100f, 100f))+ assertEquals(0.1f, clip[1], 0.0001f)+ }++ @Test+ fun clip_lengths_invalid_return_null() {+ assertNull(OdfParser.parseClipLengths(null, 100f, 100f))+ assertNull(OdfParser.parseClipLengths("rect(10px 0px 0px 0px)", 0f, 100f))+ assertNull(OdfParser.parseClipLengths("rect(0px 0px 0px 0px)", 100f, 100f))+ assertNull(OdfParser.parseClipLengths("nope", 100f, 100f))+ }++ // --- parseRotationDegrees ---++ @Test+ fun rotation_radians_to_clockwise_degrees() {+ // rotate() is counter-clockwise radians; result is clockwise degrees.+ assertEquals(-90f, OdfParser.parseRotationDegrees("rotate(1.5707963)"), 0.01f)+ assertEquals(0f, OdfParser.parseRotationDegrees(null), 0.001f)+ assertEquals(0f, OdfParser.parseRotationDegrees("translate(10)"), 0.001f)+ assertEquals(0f, OdfParser.parseRotationDegrees("rotate(oops)"), 0.001f)+ }++ // --- formulaBlock (via body paragraphs with embedded objects) ---++ private val mathHead =+ """<?xml version="1.0" encoding="UTF-8"?>""" ++ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink">"""++ @Test+ fun formula_block_math_vs_plain() {+ // Embedded math content in a body paragraph becomes a Formula block;+ // other embedded content becomes a centered italic placeholder paragraph.+ val doc = OdfParser.parseTextDocument(+ mathHead ++ "<office:body><office:text>" ++ """<text:p><draw:object xlink:href="./Object 1"/></text:p>""" ++ """<text:p><draw:object xlink:href="./Object 2"/></text:p>""" ++ "</office:text></office:body></office:document>",+ emptyMap(), emptyMap(), "t",+ com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), null,+ mapOf(+ "Object 1/content.xml" to "<math xmlns:m=\"urn:math\"><m:mi>x</m:mi></math>",+ "Object 2/content.xml" to "<office:spreadsheet xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"/>"+ )+ )+ val formula = doc.content.filterIsInstance<OdfContentBlock.Formula>().single()+ assertEquals("<math xmlns:m=\"urn:math\"><m:mi>x</m:mi></math>", formula.mathml)+ // The empty first paragraph is dropped; only the spreadsheet placeholder remains.+ val paras = doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+ assertEquals(1, paras.size)+ val placeholder = paras.single().paragraph+ assertTrue(placeholder.spans.single().text.contains("Embedded spreadsheet"))+ assertTrue(placeholder.spans.single().italic)+ assertEquals(TextAlign.Center, placeholder.alignment)+ }++ // --- parseDirection ---++ @Test+ fun direction_from_writing_mode() {+ assertEquals(LayoutDirection.Rtl, OdfParser.parseDirection("rl-tb"))+ assertEquals(LayoutDirection.Ltr, OdfParser.parseDirection("lr-tb"))+ assertNull(OdfParser.parseDirection(null))+ assertNull(OdfParser.parseDirection("tb"))+ }++ // --- unescapeXml / parseFormulaText ---++ @Test+ fun unescape_xml_entities() {+ assertEquals("<a \"b\" & 'c'>", OdfParser.unescapeXml("<a "b" & 'c'>"))+ }++ @Test+ fun formula_text_prefers_annotation() {+ val xml = "<math><annotation>x+y < z</annotation><m:mi>x</m:mi></math>"+ assertEquals("x+y < z", OdfParser.parseFormulaText(xml))+ }++ @Test+ fun formula_text_joins_math_tokens() {+ val xml = "<math xmlns:m=\"m\"><m:mi>x</m:mi><m:mo>+</m:mo><m:mn>2</m:mn></math>"+ assertEquals("x + 2", OdfParser.parseFormulaText(xml))+ val plain = "<math><mi>a</mi><mo>=</mo><mi>b</mi></math>"+ assertEquals("a = b", OdfParser.parseFormulaText(plain))+ }++ @Test+ fun formula_text_no_math_returns_null() {+ assertNull(OdfParser.parseFormulaText("<office:text><text:p>hi</text:p></office:text>"))+ assertNull(OdfParser.parseFormulaText("<math></math>"))+ assertNotNull(OdfParser.parseFormulaText("<math><m:mi>x</m:mi></math>"))+ }++ @Test+ fun link_color_constant() {+ assertEquals(0xFF0066CCL, OdfParser.LINK_COLOR)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2InlineTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2InlineTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2InlineTest.ktnew file mode 100644index 0000000000..8b599b308e--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2InlineTest.kt@@ -0,0 +1,298 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfSpan+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.xmlpull.v1.XmlPullParser++/**+ * Slice 2/4 (OdfParser*): inline content — spans, links, whitespace elements,+ * footnotes, annotations, fields, cross-references and inline objects/images.+ */+class OdfParser2InlineTest {++ private val head =+ """<?xml version="1.0" encoding="UTF-8"?>""" ++ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink" """ ++ """xmlns:dc="http://purl.org/dc/elements/1.1/">"""++ private fun doc(body: String): OdfDocument.TextDocument = OdfParser.parseTextXml(+ head ++ "<office:automatic-styles/>" ++ "<office:body><office:text>$body</office:text></office:body></office:document>"+ )++ private fun paraSpans(body: String) =+ doc(body).content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph }.single().spans++ /** Runs [OdfParser.parseInlineContent] over a bare `<text:p>` fragment. */+ private fun inlineSpans(+ fragment: String,+ styles: Map<String, StyleInfo> = emptyMap(),+ images: Map<String, ByteArray> = emptyMap(),+ imagesOut: MutableList<OdfImage>? = null,+ objectContents: Map<String, String> = emptyMap(),+ formulasOut: MutableList<String>? = null,+ ): List<OdfSpan> {+ val parser = OdfParser.newParser(+ """<w xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0">""" ++ fragment + "</w>"+ )+ var e = parser.eventType+ while (!(e == XmlPullParser.START_TAG && parser.name == "p")) e = parser.next()+ return OdfParser.parseInlineContent(parser, "p", styles, images, null, imagesOut, objectContents, null, formulasOut)+ }++ // --- Basic spans / links / whitespace ---++ @Test+ fun styled_span_and_link() {+ val stylesXml =+ """<style:style xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """style:name="B" style:family="text">""" ++ """<style:text-properties fo:font-weight="bold" fo:font-style="italic"/>""" ++ """</style:style>"""+ val styles = OdfParser.parseStyles(stylesXml)+ val spans = inlineSpans(+ """<text:p>plain<text:span text:style-name="B">bold</text:span>""" ++ """<text:a xlink:href="https://example.com">click</text:a>tail</text:p>""",+ styles+ )+ assertEquals("plain", spans[0].text)+ assertTrue(spans[1].bold && spans[1].italic)+ assertEquals("click", spans[2].text)+ assertEquals("https://example.com", spans[2].href)+ assertTrue(spans[2].underline)+ assertEquals(OdfParser.LINK_COLOR, spans[2].color)+ assertEquals("tail", spans[3].text)+ }++ @Test+ fun whitespace_elements_expand() {+ val spans = inlineSpans("""<text:p>a<text:s text:c="3"/>b<text:tab/>c<text:line-break/>d</text:p>""")+ assertEquals("a b\tc\nd", spans.single().text)+ }++ @Test+ fun make_span_link_color_fallback_only_without_style_color() {+ val stylesXml =+ """<style:style xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """style:name="R" style:family="text">""" ++ """<style:text-properties fo:color="#ff0000"/>""" ++ """</style:style>"""+ val styles = OdfParser.parseStyles(stylesXml)+ val linked = OdfParser.makeSpan("x", "R", styles, "https://e.com")+ assertEquals("https://e.com", linked.href)+ assertEquals(0xFFFF0000L, linked.color)+ assertTrue(linked.underline)+ val unstyled = OdfParser.makeSpan("y", null, styles, "https://e.com")+ assertEquals(OdfParser.LINK_COLOR, unstyled.color)+ }++ // --- Footnotes / annotations ---++ @Test+ fun footnote_citation_span_and_body() {+ val d = doc(+ """<text:p>text<text:note text:note-class="footnote">""" ++ """<text:note-citation>1</text:note-citation>""" ++ """<text:note-body><text:p>fn body</text:p></text:note-body>""" ++ """</text:note>after</text:p>"""+ )+ val spans = d.content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph }.single().spans+ assertEquals(listOf("text", "1", "after"), spans.map { it.text })+ assertTrue(spans[1].superscript)+ assertEquals(1, d.footnotes.size)+ assertEquals("1", d.footnotes.single().citation)+ assertEquals("fn body", d.footnotes.single().body.single().spans.single().text)+ }++ @Test+ fun endnote_flag_and_missing_citation() {+ val d = doc(+ """<text:p>a<text:note text:note-class="endnote">""" ++ """<text:note-citation>i</text:note-citation><text:note-body><text:p>b</text:p></text:note-body>""" ++ """</text:note><text:note><text:note-body><text:p>no citation</text:p></text:note-body></text:note></text:p>"""+ )+ assertTrue(d.footnotes.single().isEndnote)+ // The citation-less note produces no span.+ assertEquals(listOf("a", "i"), d.content+ .mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph }.single().spans.map { it.text })+ }++ @Test+ fun annotation_span_carries_author_and_comment() {+ val spans = paraSpans(+ """<text:p>hi<office:annotation><dc:creator>Bob</dc:creator><dc:date>2024-05-01</dc:date>""" ++ """<text:p>comment!</text:p></office:annotation></text:p>"""+ )+ assertEquals("hi", spans[0].text)+ assertEquals(" 📝 ", spans[1].text)+ val ann = assertNotNull(spans[1].annotation)+ assertEquals("Bob", ann.author)+ assertEquals("2024-05-01", ann.date)+ assertEquals("comment!", ann.paragraphs.single().spans.single().text)+ }++ // --- Fields / references / bookmarks ---++ @Test+ fun text_fields_become_field_spans() {+ val spans = paraSpans(+ """<text:p><text:date>2024-01-02</text:date> <text:page-number>3</text:page-number> """ ++ """<text:page-count>10</text:page-count> <text:title>My Doc</text:title></text:p>"""+ )+ assertEquals(listOf("2024-01-02", " ", "3", " ", "10", " ", "My Doc"), spans.map { it.text })+ assertEquals("date", spans[0].field)+ assertEquals("page-number", spans[2].field)+ assertEquals("page-count", spans[4].field)+ assertEquals("title", spans[6].field)+ assertNull(spans[1].field)+ }++ @Test+ fun reference_ref_span_has_target_and_format() {+ val spans = paraSpans(+ """<text:p>see <text:reference-ref text:ref-name="R1" text:reference-format="page">12</text:reference-ref></text:p>"""+ )+ val ref = spans.single { it.refKind == "reference-ref" }+ assertEquals("12", ref.text)+ assertEquals("R1", ref.refName)+ assertEquals("page", ref.refFormat)+ assertEquals(OdfParser.LINK_COLOR, ref.color)+ }++ @Test+ fun bookmark_marks_produce_zero_width_spans() {+ val spans = paraSpans(+ """<text:p>a<text:bookmark text:name="B1"/><text:reference-mark text:name="M1"/>b</text:p>"""+ )+ assertEquals("", spans[1].text)+ assertEquals("bookmark", spans[1].refKind)+ assertEquals("B1", spans[1].refName)+ assertEquals("reference-mark", spans[2].refKind)+ assertEquals("M1", spans[2].refName)+ }++ // --- Inline objects ---++ @Test+ fun inline_object_branches() {+ val formulas = mutableListOf<String>()+ inlineSpans(+ """<text:p>x<draw:object xlink:href="./Object 1"/><draw:object xlink:href="./Object 2"/>""" ++ """<draw:object xlink:href="./Object 3"/><draw:object xlink:href="./Object 4"/>""" ++ """<draw:object xlink:href="./Missing"/>y</text:p>""",+ objectContents = mapOf(+ "Object 1/content.xml" to "<math xmlns:m=\"urn:math\"><m:mi>x</m:mi></math>",+ "Object 2/content.xml" to "<office:spreadsheet xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"/>",+ "Object 3/content.xml" to "<office:text xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"/>",+ "Object 4/content.xml" to "<blob/>"+ ),+ formulasOut = formulas+ )+ assertEquals(+ listOf(+ "<math xmlns:m=\"urn:math\"><m:mi>x</m:mi></math>",+ "📊 [Embedded spreadsheet]",+ "📄 [Embedded document]",+ "📦 [Embedded object]",+ "📦 [Embedded object]"+ ),+ formulas+ )+ }++ @Test+ fun inline_object_chart_branch() {+ val chartXml =+ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" """ ++ """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:office2="urn:oasis:names:tc:opendocument:xmlns:office:1.0">""" ++ """<office:body><office:text>""" ++ """<chart:chart chart:class="chart:line"><chart:title><text:p>T</text:p></chart:title>""" ++ """<table:table table:name="local-table">""" ++ """<table:table-row><table:table-cell><text:p></text:p></table:table-cell>""" ++ """<table:table-cell><text:p>S</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p>A</text:p></table:table-cell>""" ++ """<table:table-cell table:value="5"><text:p>5</text:p></table:table-cell></table:table-row>""" ++ """</table:table></chart:chart></office:text></office:body></office:document>"""+ val charts = mutableListOf<com.vayunmathur.library.ui.odf.OdfChart>()+ val parser = OdfParser.newParser(+ """<w xmlns:text="urn:t" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink">""" ++ """<text:p><draw:object xlink:href="./Object 9"/></text:p></w>"""+ )+ var e = parser.eventType+ while (!(e == XmlPullParser.START_TAG && parser.name == "p")) e = parser.next()+ OdfParser.parseInlineContent(parser, "p", emptyMap(), emptyMap(), null, null,+ mapOf("Object 9/content.xml" to chartXml), charts, null)+ assertEquals(1, charts.size)+ assertEquals("S", charts.single().series.single().name)+ }++ // --- Inline images (packaged path; bitmap decode is stubbed on JVM) ---++ @Test+ fun packaged_inline_image_with_clip_and_svg_alt_text() {+ val imagesOut = mutableListOf<OdfImage>()+ val spans = inlineSpans(+ """<text:p>t<draw:frame draw:name="f" svg:width="2cm" svg:height="1cm" fo:clip="rect(10% 0% 0% 0%)">""" ++ """<draw:image xlink:href="Pictures/a.png"/>""" ++ """<svg:title>Alt title</svg:title><svg:desc>Alt desc</svg:desc>""" ++ """</draw:frame></text:p>""",+ images = mapOf("Pictures/a.png" to byteArrayOf(1, 2, 3)),+ imagesOut = imagesOut+ )+ assertEquals("t", spans.single().text)+ val img = imagesOut.single()+ assertEquals("Pictures/a.png", img.path)+ assertEquals(2f * 37.8f, img.width, 0.01f)+ assertEquals(0.1f, img.cropTopPct, 0.0001f)+ assertEquals("Alt title", img.altTitle)+ assertEquals("Alt desc", img.altDesc)+ }++ @Test+ fun unknown_image_href_emits_nothing() {+ val imagesOut = mutableListOf<OdfImage>()+ val spans = inlineSpans(+ """<text:p>t<draw:frame draw:name="f"><draw:image xlink:href="Pictures/nope.png"/>""" ++ """</draw:frame></text:p>""",+ imagesOut = imagesOut+ )+ assertEquals("t", spans.single().text)+ assertTrue(imagesOut.isEmpty())+ }++ @Test+ fun svg_alt_text_without_image_is_dropped() {+ val imagesOut = mutableListOf<OdfImage>()+ val spans = inlineSpans(+ """<text:p>t<svg:title>Orphan</svg:title></text:p>""",+ imagesOut = imagesOut+ )+ assertEquals("t", spans.single().text)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2MediaRoboTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2MediaRoboTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2MediaRoboTest.ktnew file mode 100644index 0000000000..357c44bf5d--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2MediaRoboTest.kt@@ -0,0 +1,167 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfImage+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+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.xmlpull.v1.XmlPullParser++/**+ * Slice 2/4 (OdfParser*), Robolectric part: inline base64 images+ * ([OdfParser.readInlineImageData]) need android.util.Base64, which is a stub+ * on plain JVM tests. Also covers frame-embedded base64 images and the+ * packaged-image clip fallback via graphic-style clip.+ */+@RunWith(RobolectricTestRunner::class)+class OdfParser2MediaRoboTest {++ private val head =+ """<?xml version="1.0" encoding="UTF-8"?>""" ++ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0">"""++ // 1x1 transparent PNG.+ private val tinyPng =+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="++ /** Runs [OdfParser.parseInlineContent] over a bare `<text:p>` fragment. */+ private fun inlineSpans(+ fragment: String,+ imagesOut: MutableList<OdfImage>? = null,+ ): List<com.vayunmathur.library.ui.odf.OdfSpan> {+ val parser = OdfParser.newParser(+ """<w xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0">""" ++ fragment + "</w>"+ )+ var e = parser.eventType+ while (!(e == XmlPullParser.START_TAG && parser.name == "p")) e = parser.next()+ return OdfParser.parseInlineContent(parser, "p", emptyMap(), emptyMap(), null, imagesOut)+ }++ @Test+ fun inline_base64_image_decoded() {+ val imagesOut = mutableListOf<OdfImage>()+ inlineSpans(+ """<text:p>t<draw:frame draw:name="f" svg:width="2cm" svg:height="1cm">""" ++ """<draw:image><office:binary-data xmlns:office="urn:o">""" + tinyPng ++ """</office:binary-data></draw:image></draw:frame></text:p>""",+ imagesOut+ )+ val img = imagesOut.single()+ assertEquals("inline", img.path)+ assertTrue(img.imageData.isNotEmpty())+ assertEquals(2f * 37.8f, img.width, 0.01f)+ }++ @Test+ fun inline_invalid_base64_skipped() {+ val imagesOut = mutableListOf<OdfImage>()+ inlineSpans(+ """<text:p>t<draw:frame draw:name="f"><draw:image>""" ++ """<office:binary-data xmlns:office="urn:o">!!!not-base64!!!</office:binary-data>""" ++ """</draw:image></draw:frame></text:p>""",+ imagesOut+ )+ assertTrue(imagesOut.isEmpty())+ }++ @Test+ fun frame_base64_image_with_opacity() {+ val autoStyles =+ """<style:style style:name="op" style:family="graphic">""" ++ """<style:graphic-properties style:image-opacity="80%"/>""" ++ """</style:style>"""+ val d = OdfParser.parsePresentation(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:presentation>" ++ """<draw:page draw:name="S1">""" ++ """<draw:frame draw:name="f" svg:x="0" svg:y="0" svg:width="3cm" svg:height="2cm">""" ++ """<draw:image draw:style-name="op"><office:binary-data xmlns:office="urn:o">""" + tinyPng ++ """</office:binary-data></draw:image></draw:frame></draw:page>""" ++ "</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ "t", com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap()+ )+ val frame = (d.slides.single().elements.single() as OdfSlideElement.Frame).frame+ val img = assertNotNull(frame.image)+ assertEquals("inline", img.path)+ assertEquals(3f * 37.8f, img.width, 0.01f)+ assertEquals(80f, img.opacityPercent)+ }++ @Test+ fun packaged_image_style_clip_fallback() {+ // No fo:clip on the frame; the graphic style's fo:clip is parsed (style+ // "clip" resolves with the raw rect). Natural size is 0 under the test+ // runtime (no bitmap decoder), so image crops can't resolve — assert the+ // image itself plus parseClip's [left, top, right, bottom] contract.+ val autoStyles =+ """<style:style style:name="clip" style:family="graphic">""" ++ """<style:graphic-properties fo:clip="rect(10% 20% 30% 40%)"/>""" ++ """</style:style>"""+ val png = android.util.Base64.decode(tinyPng, android.util.Base64.DEFAULT)+ val d = OdfParser.parsePresentation(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:presentation>" ++ """<draw:page draw:name="S1">""" ++ """<draw:frame draw:name="f" svg:x="0" svg:y="0" svg:width="3cm" svg:height="2cm">""" ++ """<draw:image xlink:href="Pictures/p.png" draw:style-name="clip"/>""" ++ """</draw:frame></draw:page>""" ++ "</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ "t", com.vayunmathur.library.ui.odf.OdfMetadata(),+ mapOf("Pictures/p.png" to png), emptyMap()+ )+ val img = assertNotNull((d.slides.single().elements.single() as OdfSlideElement.Frame).frame.image)+ assertEquals("Pictures/p.png", img.path)+ assertEquals(png.size, img.imageData.size)+ // parseClip("rect(top right bottom left)") -> [left, top, right, bottom].+ val clip = assertNotNull(OdfParser.parseClip("rect(10% 20% 30% 40%)"))+ assertEquals(0.4f, clip[0], 0.0001f)+ assertEquals(0.1f, clip[1], 0.0001f)+ assertEquals(0.2f, clip[2], 0.0001f)+ assertEquals(0.3f, clip[3], 0.0001f)+ }++ @Test+ fun footnote_without_footnotes_out_still_adds_span() {+ // footnotes == null: citation span still emitted.+ val parser = OdfParser.newParser(+ """<w xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">""" ++ """<text:p>a<text:note><text:note-citation>2</text:note-citation>""" ++ """<text:note-body><text:p>body</text:p></text:note-body></text:note></text:p></w>"""+ )+ var e = parser.eventType+ while (!(e == XmlPullParser.START_TAG && parser.name == "p")) e = parser.next()+ val spans = OdfParser.parseInlineContent(parser, "p", emptyMap(), emptyMap(), null)+ assertEquals(listOf("a", "2"), spans.map { it.text })+ assertTrue(spans[1].superscript)+ }++ @Test+ fun empty_annotation_yields_marker_with_empty_comment() {+ val parser = OdfParser.newParser(+ """<w xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:dc="http://purl.org/dc/elements/1.1" xmlns:office="urn:o">""" ++ """<text:p>a<office:annotation><dc:creator></dc:creator></office:annotation></text:p></w>"""+ )+ var e = parser.eventType+ while (!(e == XmlPullParser.START_TAG && parser.name == "p")) e = parser.next()+ val spans = OdfParser.parseInlineContent(parser, "p", emptyMap())+ assertEquals("a", spans.first().text)+ assertNotNull(spans.last().annotation)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2SheetTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2SheetTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2SheetTest.ktnew file mode 100644index 0000000000..6ba6ab51cf--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2SheetTest.kt@@ -0,0 +1,341 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfDocument+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 2/4 (OdfParser*): spreadsheet parsing (sheets, rows, cells, repeats,+ * hidden rows/cols, named ranges, validations, cell content) and CSV import.+ */+class OdfParser2SheetTest {++ private val head =+ """<?xml version="1.0" encoding="UTF-8"?>""" ++ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:dc="http://purl.org/dc/elements/1.1/">"""++ private fun sheet(+ body: String,+ autoStyles: String = "",+ freeze: Map<String, Pair<Int, Int>> = emptyMap(),+ ): OdfDocument.Spreadsheet = OdfParser.parseSpreadsheet(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:spreadsheet>$body</office:spreadsheet></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ emptyMap(),+ "test",+ com.vayunmathur.library.ui.odf.OdfMetadata(),+ emptyMap(),+ emptyMap(),+ freeze+ )++ private fun cell(sheetBody: String, row: Int = 0, col: Int = 0): OdfCell =+ sheet(sheetBody).sheets.single().rows[row].cells[col]++ // --- Basic cells ---++ @Test+ fun text_and_numeric_cells() {+ val c0 = cell(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell office:value-type="string"><text:p>hello</text:p></table:table-cell>""" ++ """<table:table-cell office:value-type="float" office:value="3.5"><text:p>3.5</text:p></table:table-cell>""" ++ """</table:table-row></table:table>"""+ )+ assertEquals("hello", c0.text)+ assertEquals("string", c0.valueType)+ val c1 = sheet(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell office:value-type="float" office:value="3.5"><text:p>3.5</text:p></table:table-cell>""" ++ """</table:table-row></table:table>"""+ ).sheets.single().rows[0].cells[0]+ assertEquals(3.5, c1.numberValue)+ assertEquals("float", c1.valueType)+ }++ @Test+ fun formula_cells_keep_openformula_source() {+ val c = cell(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell table:formula="of:=SUM([.A1:.A3])" """ ++ """office:value-type="float" office:value="6"><text:p>6</text:p></table:table-cell>""" ++ """</table:table-row></table:table>"""+ )+ assertEquals("of:=SUM([.A1:.A3])", c.formula)+ }++ @Test+ fun merged_and_covered_cells() {+ val s = sheet(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell table:number-columns-spanned="2" table:number-rows-spanned="3">""" ++ """<text:p>M</text:p></table:table-cell>""" ++ """<table:covered-table-cell/>""" ++ """<table:table-cell table:number-columns-repeated="2"><text:p>R</text:p></table:table-cell>""" ++ """</table:table-row></table:table>"""+ )+ val row = s.sheets.single().rows.single()+ assertEquals(2, row.cells[0].spannedColumns)+ assertEquals(3, row.cells[0].rowSpan)+ assertTrue(row.cells[1].isCovered)+ assertEquals(4, row.cells.size)+ assertEquals("R", row.cells[2].text)+ assertEquals("R", row.cells[3].text)+ }++ @Test+ fun trailing_filler_cells_trimmed_but_styled_kept() {+ val styles = """<style:style style:name="HL" style:family="table-cell">""" ++ """<style:table-cell-properties fo:background-color="#ffff00"/>""" ++ """</style:style>"""+ val s = sheet(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell><text:p>A</text:p></table:table-cell>""" ++ """<table:table-cell table:style-name="HL"><text:p/></table:table-cell>""" ++ """<table:table-cell table:number-columns-repeated="10"><text:p/></table:table-cell>""" ++ """</table:table-row></table:table>""",+ styles+ )+ val row = s.sheets.single().rows.single()+ // Trailing unstyled fillers trimmed; the styled (highlighted) empty cell is kept.+ assertEquals(2, row.cells.size)+ assertEquals("A", row.cells[0].text)+ assertEquals(0xFFFFFF00L, row.cells[1].backgroundColor)+ }++ @Test+ fun trailing_empty_rows_trimmed() {+ val s = sheet(+ """<table:table table:name="S">""" ++ """<table:table-row><table:table-cell><text:p>data</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p/></table:table-cell></table:table-row>""" ++ """</table:table>"""+ )+ assertEquals(1, s.sheets.single().rows.size)+ }++ // --- Rows / columns / hidden / widths ---++ @Test+ fun repeated_rows_hidden_rows_and_heights() {+ val styles = """<style:style style:name="RH" style:family="table-row">""" ++ """<style:table-row-properties style:row-height="2cm"/>""" ++ """</style:style>"""+ val s = sheet(+ """<table:table table:name="S">""" ++ """<table:table-column table:style-name="nope"/>""" ++ """<table:table-row><table:table-cell><text:p>a</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row table:number-rows-repeated="3"><table:table-cell><text:p>r</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row table:style-name="RH" table:visibility="collapse">""" ++ """<table:table-cell><text:p>h</text:p></table:table-cell></table:table-row>""" ++ """</table:table>""",+ styles+ )+ val sh = s.sheets.single()+ assertEquals(5, sh.rows.size)+ assertEquals(setOf(4), sh.hiddenRows)+ assertEquals(2 * 37.8f, sh.rowHeights[4] ?: 0f, 0.01f)+ }++ @Test+ fun column_widths_and_hidden_columns() {+ val styles = """<style:style style:name="W" style:family="table-column">""" ++ """<style:table-column-properties style:column-width="4cm"/>""" ++ """</style:style>"""+ val s = sheet(+ """<table:table table:name="S">""" ++ """<table:table-column table:style-name="W"/>""" ++ """<table:table-column table:number-columns-repeated="2" table:visibility="filter"/>""" ++ """<table:table-row><table:table-cell><text:p>a</text:p></table:table-cell></table:table-row>""" ++ """</table:table>""",+ styles+ )+ val sh = s.sheets.single()+ assertEquals(3, sh.columnWidths.size)+ assertEquals(4 * 37.8f, sh.columnWidths[0] ?: 0f, 0.01f)+ assertEquals(setOf(1, 2), sh.hiddenCols)+ }++ @Test+ fun freeze_panes_print_ranges_and_default_sheet_name() {+ val s = sheet(+ """<table:table table:name="Data" table:print-ranges="Data.A1:Data.B2">""" ++ """<table:table-row><table:table-cell><text:p>x</text:p></table:table-cell></table:table-row>""" ++ """</table:table>""" ++ """<table:table><table:table-row><table:table-cell><text:p>y</text:p></table:table-cell></table:table-row></table:table>""",+ freeze = mapOf("Data" to (1 to 2))+ )+ assertEquals("Data", s.sheets[0].name)+ assertEquals(1, s.sheets[0].freezeRows)+ assertEquals(2, s.sheets[0].freezeCols)+ assertEquals("Data.A1:Data.B2", s.sheets[0].printRanges)+ assertEquals("Sheet 2", s.sheets[1].name)+ assertEquals(0, s.sheets[1].freezeRows)+ }++ // --- Named ranges / validations / conditional formats ---++ @Test+ fun named_ranges_and_validations() {+ val s = sheet(+ """<table:named-range table:name="Total" table:cell-range-address="S.${'$'}A${'$'}1" table:base-cell-address="S.${'$'}A${'$'}1"/>""" ++ """<table:content-validation table:name="V1" table:condition="cell-content-is-in-list("a;b")" """ ++ """table:allow-empty-cell="false"/>""" ++ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell table:content-validation-name="V1"><text:p>a</text:p></table:table-cell>""" ++ """</table:table-row></table:table>"""+ )+ assertEquals(1, s.namedRanges.size)+ assertEquals("Total", s.namedRanges.single().name)+ assertEquals("S.\$A\$1", s.namedRanges.single().cellRangeAddress)+ assertEquals(1, s.validations.size)+ assertEquals("V1", s.validations.single().name)+ assertFalse(s.validations.single().allowEmpty)+ assertEquals(listOf("a", "b"), s.validations.single().listValues())+ assertEquals("V1", s.sheets.single().rows.single().cells.single().validationName)+ }++ @Test+ fun conditional_formats_resolved_from_style_map() {+ val styles = """<style:style style:name="High" style:family="table-cell">""" ++ """<style:table-cell-properties fo:background-color="#ff0000"/>""" ++ """</style:style>""" ++ """<style:style style:name="Base" style:family="table-cell">""" ++ """<style:table-cell-properties><style:map style:condition="cell-content()>5" """ ++ """style:apply-style-name="High"/></style:table-cell-properties></style:style>"""+ val c = cell(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell table:style-name="Base"><text:p>9</text:p></table:table-cell>""" ++ """</table:table-row></table:table>""",+ 0, 0+ )+ // Re-parse with styles wired through (the helper above already does).+ val s = sheet(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell table:style-name="Base"><text:p>9</text:p></table:table-cell>""" ++ """</table:table-row></table:table>""",+ styles+ )+ val cf = s.sheets.single().rows.single().cells.single().condFormats.single()+ assertEquals("cell-content()>5", cf.condition)+ assertEquals(0xFFFF0000L, cf.backgroundColor)+ assertEquals("9", s.sheets.single().rows.single().cells.single().text)+ assertEquals("9", c.text)+ }++ // --- Cell content details ---++ @Test+ fun cell_content_whitespace_and_annotation() {+ val s = sheet(+ """<table:table table:name="S"><table:table-row><table:table-cell>""" ++ """<text:p>line1</text:p><text:p>line2<text:s text:c="2"/>x<text:tab/>y<text:line-break/>z</text:p>""" ++ """<office:annotation><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1">Ann</dc:creator>""" ++ """<text:p>note</text:p></office:annotation>""" ++ """</table:table-cell></table:table-row></table:table>"""+ )+ val c = s.sheets.single().rows.single().cells.single()+ assertEquals("line1\nline2 x\ty\nz", c.text)+ assertEquals("Ann", c.annotation!!.author)+ assertEquals("note", c.annotation!!.paragraphs.single().spans.single().text)+ }++ @Test+ fun cell_number_format_from_data_style() {+ val autoStyles =+ """<number:number-style style:name="N2" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0">""" ++ """<number:number number:decimal-places="2" number:grouping="true"/></number:number-style>""" ++ """<style:style style:name="Num" style:family="table-cell" style:data-style-name="N2"/>"""+ val st = OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>")+ val ns = OdfParser.parseNumberStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>")+ assertEquals(2, ns["N2"]!!.decimals)+ assertTrue(ns["N2"]!!.grouping)+ val s = OdfParser.parseSpreadsheet(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ """<office:body><office:spreadsheet><table:table table:name="S"><table:table-row>""" ++ """<table:table-cell table:style-name="Num" office:value-type="float" office:value="1.5">""" ++ """<text:p>1.50</text:p></table:table-cell></table:table-row></table:table>""" ++ """</office:spreadsheet></office:body></office:document>""",+ st, ns, "t",+ com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap(), emptyMap()+ )+ assertEquals(2, s.sheets.single().rows.single().cells.single().numberFormat!!.decimals)+ }++ // --- CSV ---++ @Test+ fun csv_basic_quoted_and_escaped() {+ val doc = OdfParser.parseCsv("a,b,c\n\"x,y\",\"q\"\"q\",z\n", "f.csv")+ assertEquals("f.csv", doc.title)+ val rows = doc.sheets.single().rows+ assertEquals(2, rows.size)+ assertEquals(listOf("a", "b", "c"), rows[0].cells.map { it.text })+ assertEquals(listOf("x,y", "q\"q", "z"), rows[1].cells.map { it.text })+ }++ @Test+ fun csv_quoted_newlines_crlf_and_blank_lines() {+ // A quoted field absorbs the \r\n; the standalone \r\n after the closing quote+ // ends the record. Blank/whitespace-only records are skipped.+ val doc = OdfParser.parseCsv("a,\"multi\r\nline\"\r\n,,kept\r\n\r\n \nlast", "f.csv", ',')+ val rows = doc.sheets.single().rows+ assertEquals(3, rows.size)+ assertEquals("multi\r\nline", rows[0].cells[1].text)+ assertEquals(listOf("", "", "kept"), rows[1].cells.map { it.text })+ assertEquals("last", rows[2].cells.single().text)+ }++ @Test+ fun csv_custom_delimiter_and_unterminated_quote() {+ val doc = OdfParser.parseCsv("a;b\nc;d", "f.csv", ';')+ assertEquals(listOf("a", "b"), doc.sheets.single().rows[0].cells.map { it.text })+ val unterminated = OdfParser.parseCsv("\"abc", "u.csv")+ assertEquals("abc", unterminated.sheets.single().rows.single().cells.single().text)+ }++ @Test+ fun csv_single_sheet_named_sheet_1() {+ val doc = OdfParser.parseCsv("only", "o.csv")+ assertEquals("Sheet 1", doc.sheets.single().name)+ assertIs<OdfDocument.Spreadsheet>(doc)+ }++ // --- Floating drawings in sheets ---++ @Test+ fun sheet_drawings_collected_as_floating() {+ val s = sheet(+ """<table:table table:name="S">""" ++ """<table:table-row><table:table-cell><text:p>v</text:p></table:table-cell></table:table-row>""" ++ """<draw:rect draw:name="r" svg:x="1cm" svg:y="1cm" svg:width="2cm" svg:height="1cm" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"/>""" ++ """</table:table>"""+ )+ assertEquals(1, s.sheets.single().floating.size)+ assertIs<com.vayunmathur.library.ui.odf.OdfSlideElement.Shape>(s.sheets.single().floating.single())+ }++ @Test+ fun non_draw_namespaced_tags_ignored_in_sheet() {+ val s = sheet(+ """<table:table table:name="S"><table:table-row>""" ++ """<table:table-cell><text:p>v</text:p></table:table-cell></table:table-row>""" ++ """<text:p>not a drawing</text:p></table:table>"""+ )+ assertTrue(s.sheets.single().floating.isEmpty())+ assertEquals("v", s.sheets.single().rows.single().cells.single().text)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2SlidesTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2SlidesTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2SlidesTest.ktnew file mode 100644index 0000000000..bfcf2284f8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2SlidesTest.kt@@ -0,0 +1,399 @@+package com.vayunmathur.office.odf++import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.xmlpull.v1.XmlPullParser++/**+ * Slice 2/4 (OdfParser*): presentations/drawings — slides, frames, text boxes,+ * lists in frames, all shape kinds, notes, SVG path sampling and poly points.+ */+class OdfParser2SlidesTest {++ private val head =+ """<?xml version="1.0" encoding="UTF-8"?>""" ++ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" """ ++ """xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink">"""++ private fun presentation(+ pages: String,+ autoStyles: String = "",+ title: String = "deck",+ ): OdfDocument.Presentation = OdfParser.parsePresentation(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:presentation>$pages</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ title,+ com.vayunmathur.library.ui.odf.OdfMetadata(),+ emptyMap(),+ emptyMap()+ )++ private fun frame(name: String = "f", inner: String = "", attrs: String = "") =+ """<draw:frame draw:name="$name" svg:x="1cm" svg:y="2cm" svg:width="5cm" svg:height="3cm" $attrs>$inner</draw:frame>"""++ private fun page(name: String = "Slide 1", inner: String = "", attrs: String = "") =+ """<draw:page draw:name="$name" $attrs>$inner</draw:page>"""++ // --- Slides ---++ @Test+ fun slides_default_names_and_master() {+ val d = presentation(page() + page("Second", attrs = """draw:master-page-name="M1""""))+ assertEquals("deck", d.title)+ assertEquals(2, d.slides.size)+ assertEquals("Slide 1", d.slides[0].name)+ assertNull(d.slides[0].masterName)+ assertEquals("M1", d.slides[1].masterName)+ }++ @Test+ fun slide_background_and_transition_from_style() {+ val autoStyles =+ """<style:style style:name="bg" style:family="drawing-page">""" ++ """<style:drawing-page-properties draw:fill="solid" draw:fill-color="#aabbcc" """ ++ """presentation:transition-style="fade" presentation:transition-speed="slow"/>""" ++ """</style:style>"""+ val d = presentation(page(attrs = """draw:style-name="bg""""), autoStyles)+ assertEquals(0xFFAABBCCL, d.slides.single().backgroundColor)+ assertEquals("fade", d.slides.single().transitionType)+ assertEquals("slow", d.slides.single().transitionSpeed)+ }++ @Test+ fun drawing_document_parses_pages() {+ val d = OdfParser.parseDrawing(+ head + "<office:body><office:drawing>" + page("P1") + "</office:drawing></office:body></office:document>",+ emptyMap(), "draw",+ com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap()+ )+ assertEquals("P1", d.pages.single().name)+ }++ // --- Frames ---++ @Test+ fun frame_geometry_and_text_box() {+ val d = presentation(page(inner = frame(inner = """<draw:text-box><text:p>Hello</text:p></draw:text-box>""")))+ val f = (d.slides.single().elements.single() as OdfSlideElement.Frame).frame+ assertEquals(37.8f, f.x, 0.01f)+ assertEquals(2 * 37.8f, f.y, 0.01f)+ assertEquals(5 * 37.8f, f.width, 0.01f)+ assertEquals(3 * 37.8f, f.height, 0.01f)+ assertEquals("Hello", f.paragraphs.single().spans.single().text)+ assertNull(f.image)+ }++ @Test+ fun frame_direct_text_paragraphs_and_rotation_anchor() {+ val d = presentation(page(inner = frame(+ attrs = """draw:transform="rotate(1.5707963)" draw:anchor-type="as-char"""",+ inner = """<text:p>direct</text:p>"""+ )))+ val f = (d.slides.single().elements.single() as OdfSlideElement.Frame).frame+ assertEquals("direct", f.paragraphs.single().spans.single().text)+ // Frame-level transform is captured for images; the frame model itself keeps 0 rotation.+ assertEquals(0f, f.rotationDegrees, 0.001f)+ }++ @Test+ fun frame_packaged_image_with_style_and_opacity() {+ val autoStyles =+ """<style:style style:name="img" style:family="graphic">""" ++ """<style:graphic-properties style:image-opacity="75%" draw:color-mode="watermark"/>""" ++ """</style:style>"""+ val d = OdfParser.parsePresentation(+ head + "<office:body><office:presentation>" ++ page(inner = frame(+ attrs = """draw:style-name="img"""",+ inner = """<draw:image xlink:href="Pictures/p.png" draw:style-name="img"/>"""+ )) + "</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ "t",+ com.vayunmathur.library.ui.odf.OdfMetadata(),+ mapOf("Pictures/p.png" to byteArrayOf(9, 9, 9)),+ emptyMap()+ )+ val img = assertNotNull((d.slides.single().elements.single() as OdfSlideElement.Frame).frame.image)+ assertEquals("Pictures/p.png", img.path)+ assertEquals(75f, img.opacityPercent)+ assertEquals("watermark", img.colorMode)+ }++ @Test+ fun frame_svg_title_desc_become_alt_text() {+ val d = presentation(page(inner = frame(inner =+ """<svg:title>My alt</svg:title><svg:desc>My desc</svg:desc>""" ++ """<draw:text-box><text:p>t</text:p></draw:text-box>"""+ )))+ val f = (d.slides.single().elements.single() as OdfSlideElement.Frame).frame+ // No image: alt text has nothing to attach to, paragraphs still parsed.+ assertEquals("t", f.paragraphs.single().spans.single().text)+ }++ @Test+ fun frame_embedded_chart_object() {+ val chartXml =+ """<doc xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" """ ++ """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0">""" ++ """<chart:chart chart:class="chart:bar"><chart:title><text:p>T</text:p></chart:title>""" ++ """<table:table table:name="local-table">""" ++ """<table:table-row><table:table-cell><text:p></text:p></table:table-cell>""" ++ """<table:table-cell><text:p>S</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:table-cell><text:p>A</text:p></table:table-cell>""" ++ """<table:table-cell table:value="2"><text:p>2</text:p></table:table-cell></table:table-row>""" ++ """</table:table></chart:chart></doc>"""+ val d = OdfParser.parsePresentation(+ head + "<office:body><office:presentation>" ++ page(inner = frame(inner = """<draw:object xlink:href="./Object 1"/>""")) ++ "</office:presentation></office:body></office:document>",+ emptyMap(), "t",+ com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(),+ mapOf("Object 1/content.xml" to chartXml)+ )+ val chart = assertNotNull((d.slides.single().elements.single() as OdfSlideElement.Frame).frame.chart)+ assertEquals("S", chart.series.single().name)+ }++ // --- Lists in frames ---++ @Test+ fun lists_in_text_box_become_list_items() {+ val d = presentation(page(inner = frame(inner =+ """<draw:text-box><text:list xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">""" ++ """<text:list-item><text:p>a</text:p>""" ++ """<text:list><text:list-item><text:p>nested</text:p></text:list-item></text:list>""" ++ """</text:list-item><text:list-item><text:p>b</text:p></text:list-item></text:list></draw:text-box>"""+ )))+ val paras = (d.slides.single().elements.single() as OdfSlideElement.Frame).frame.paragraphs+ assertEquals(listOf("a", "nested", "b"), paras.map { it.spans.single().text })+ assertTrue(paras.all { it.style == ParagraphStyle.LIST_ITEM })+ assertTrue(paras.all { it.listLevel == 1 })+ }++ // --- Shapes ---++ private fun shapeDoc(tag: String, attrs: String = "", inner: String = ""): OdfShape {+ val d = presentation(page(inner = """<$tag draw:name="s" $attrs>$inner</$tag>"""))+ return (d.slides.single().elements.single() as OdfSlideElement.Shape).shape+ }++ private val geo = """svg:x="1cm" svg:y="1cm" svg:width="4cm" svg:height="2cm""""++ @Test+ fun rect_shape_with_corners_text_and_dash() {+ val autoStyles =+ """<style:style style:name="ds" style:family="graphic">""" ++ """<style:graphic-properties draw:fill="solid" draw:fill-color="#ff0000" """ ++ """draw:stroke="dash" draw:stroke-color="#00ff00" svg:stroke-width="1pt"/>""" ++ """</style:style>"""+ val d = OdfParser.parsePresentation(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:presentation>" ++ page(inner = """<draw:rect draw:name="s" draw:style-name="ds" $geo draw:corner-radius="2mm">""" ++ """<text:p>label</text:p></draw:rect>""") ++ "</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ "t", com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap()+ )+ val r = assertIs<OdfShape.Rect>((d.slides.single().elements.single() as OdfSlideElement.Shape).shape)+ assertEquals(37.8f, r.x, 0.01f)+ assertEquals(4 * 37.8f, r.width, 0.01f)+ assertEquals(0xFFFF0000L, r.fillColor)+ assertEquals(0xFF00FF00L, r.strokeColor)+ assertTrue(r.strokeDashed)+ assertEquals(2 * 3.78f, r.cornerRadius, 0.01f)+ assertEquals("label", r.text.single().spans.single().text)+ }++ @Test+ fun ellipse_line_and_custom_shapes() {+ val e = assertIs<OdfShape.Ellipse>(shapeDoc("draw:ellipse", geo))+ assertEquals(2 * 37.8f, e.height, 0.01f)+ val l = assertIs<OdfShape.Line>(shapeDoc(+ "draw:line",+ """svg:x1="1cm" svg:y1="1cm" svg:x2="4cm" svg:y2="3cm""""+ ))+ assertEquals(3 * 37.8f, l.width, 0.01f)+ assertEquals(2 * 37.8f, l.height, 0.01f)+ val c = assertIs<OdfShape.CustomShape>(shapeDoc("draw:custom-shape", geo))+ assertEquals(4 * 37.8f, c.width, 0.01f)+ }++ @Test+ fun line_markers_parsed() {+ val autoStyles =+ """<style:style style:name="mk" style:family="graphic">""" ++ """<style:graphic-properties draw:marker-start="Arrow" draw:marker-end="Arrow"/>""" ++ """</style:style>"""+ val d = OdfParser.parsePresentation(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:presentation>" ++ page(inner = """<draw:line draw:name="s" draw:style-name="mk" """ ++ """svg:x1="1cm" svg:y1="1cm" svg:x2="4cm" svg:y2="3cm"/>""") ++ "</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ "t", com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap()+ )+ val l = assertIs<OdfShape.Line>((d.slides.single().elements.single() as OdfSlideElement.Shape).shape)+ assertTrue(l.markerStart && l.markerEnd)+ }++ @Test+ fun polyline_polygon_points_and_path() {+ val pl = assertIs<OdfShape.Polyline>(shapeDoc(+ "draw:polyline",+ geo + """ draw:points="0,0 100,0 100,50" svg:viewBox="0 0 100 50""""+ ))+ assertFalse(pl.closed)+ assertEquals(3, pl.points.size)+ assertEquals(37.8f, pl.points[0].first, 0.01f)+ val pg = assertIs<OdfShape.Polyline>(shapeDoc(+ "draw:polygon",+ geo + """ draw:points="0,0 100,0" svg:viewBox="0 0 100 50""""+ ))+ assertTrue(pg.closed)+ val path = assertIs<OdfShape.Polyline>(shapeDoc(+ "draw:path",+ geo + """ svg:viewBox="0 0 100 50" svg:d="M0,0 L100,0 L100,50 Z""""+ ))+ assertTrue(path.closed)+ assertTrue(path.points.size >= 3)+ }++ @Test+ fun shape_rotation_and_gradient_fill() {+ val grad = com.vayunmathur.library.ui.odf.OdfGradient(0xFFFF0000L, 0xFF0000FFL, 90f)+ OdfParser.gradientDefs = mapOf("g1" to grad)+ val autoStyles =+ """<style:style style:name="gs" style:family="graphic">""" ++ """<style:graphic-properties draw:fill="gradient" draw:fill-gradient-name="g1"/>""" ++ """</style:style>"""+ val d = OdfParser.parsePresentation(+ head + "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:presentation>" ++ page(inner = """<draw:rect draw:name="s" draw:style-name="gs" $geo draw:transform="rotate(3.1415926)">""" ++ """<text:p>t</text:p></draw:rect>""") ++ "</office:presentation></office:body></office:document>",+ OdfParser.parseStyles(head + "<office:automatic-styles>$autoStyles</office:automatic-styles></office:document>"),+ "t", com.vayunmathur.library.ui.odf.OdfMetadata(), emptyMap(), emptyMap()+ )+ val r = assertIs<OdfShape.Rect>((d.slides.single().elements.single() as OdfSlideElement.Shape).shape)+ assertEquals(-180f, r.rotationDegrees, 0.5f)+ assertEquals(grad, r.fillGradient)+ OdfParser.gradientDefs = emptyMap()+ }++ // --- Notes ---++ @Test+ fun slide_notes_collected_from_notes_frames() {+ val d = presentation(page(inner =+ frame(inner = """<draw:text-box><text:p>slide text</text:p></draw:text-box>""") ++ """<presentation:notes><draw:frame draw:name="n" svg:x="0" svg:y="0" svg:width="1cm" svg:height="1cm">""" ++ """<draw:text-box><text:p>speaker note</text:p></draw:text-box></draw:frame></presentation:notes>"""+ ))+ assertEquals(listOf("speaker note"), d.slides.single().notes.map { it.spans.single().text })+ }++ // --- SVG path sampling / poly points (direct unit tests) ---++ @Test+ fun svg_path_commands_sampled() {+ val (pts, closed) = OdfParser.sampleSvgPath("M0,0 L10,0 H20 V10 Z", listOf(0f, 0f, 20f, 10f), 0f, 0f, 40f, 20f)+ assertTrue(closed)+ // (0,0)->(0,0); (10,0)->(20,0); H20->(40,0); V10->(40,20); Z back to start.+ assertEquals(0f to 0f, pts.first())+ assertEquals(20f, pts[1].first, 0.001f)+ assertEquals(40f, pts[2].first, 0.001f)+ assertEquals(20f, pts[3].second, 0.001f)+ assertEquals(0f to 0f, pts.last())+ }++ @Test+ fun svg_path_relative_and_curves() {+ // No viewBox: vbW/vbH default to 1, so raw units scale by w/h (100x).+ val (rel, _) = OdfParser.sampleSvgPath("M10,10 l5,0 c0,0 5,0 5,5 s5,5 5,5", null, 0f, 0f, 100f, 100f)+ assertTrue(rel.size > 4)+ assertEquals(1000f, rel.first().first, 0.001f)+ val (quad, _) = OdfParser.sampleSvgPath("M0,0 Q10,0 10,10 T20,20", null, 0f, 0f, 10f, 10f)+ assertTrue(quad.size > 3)+ val (arc, _) = OdfParser.sampleSvgPath("M0,0 A5,5 0 0 1 10,10", null, 0f, 0f, 10f, 10f)+ assertEquals(100f, arc.last().first, 0.001f)+ }++ @Test+ fun svg_path_empty_and_unknown_command() {+ assertEquals(0, OdfParser.sampleSvgPath(null, null, 0f, 0f, 1f, 1f).first.size)+ assertEquals(0, OdfParser.sampleSvgPath(" ", null, 0f, 0f, 1f, 1f).first.size)+ // Unknown "X" command is skipped; the following L1,1 still samples+ // (10x scale: no viewBox, w=h=10).+ val (pts, _) = OdfParser.sampleSvgPath("M0,0 X5,5 L1,1", null, 0f, 0f, 10f, 10f)+ assertEquals(10f, pts.last().first, 0.001f)+ }++ @Test+ fun svg_path_relative_axis_commands() {+ // Relative h/v accumulate from the cursor: M10,10 h5 -> x=15; v5 -> y=15 (100x scale).+ val (pts, _) = OdfParser.sampleSvgPath("M10,10 h5 v5", null, 0f, 0f, 100f, 100f)+ assertEquals(1500f, pts[1].first, 0.001f)+ assertEquals(1000f, pts[1].second, 0.001f)+ assertEquals(1500f, pts.last().first, 0.001f)+ assertEquals(1500f, pts.last().second, 0.001f)+ }++ @Test+ fun path_shape_with_text_and_rotation() {+ val shape = assertIs<OdfShape.Polyline>(shapeDoc(+ "draw:path",+ geo + """ svg:viewBox="0 0 100 50" svg:d="M0,0 L100,0" draw:transform="rotate(3.1415926)"""",+ """<text:p>road</text:p>"""+ ))+ assertFalse(shape.closed)+ assertEquals("road", shape.text.single().spans.single().text)+ assertEquals(-180f, shape.rotationDegrees, 0.5f)+ }++ @Test+ fun poly_points_mapping_and_bad_input() {+ val pts = OdfParser.parsePolyPoints("0,0 50,25 bad 10,", listOf(0f, 0f, 100f, 50f), 10f, 20f, 200f, 100f)+ assertEquals(2, pts.size)+ assertEquals(10f to 20f, pts[0])+ assertEquals(110f, pts[1].first, 0.001f)+ assertEquals(70f, pts[1].second, 0.001f)+ assertTrue(OdfParser.parsePolyPoints(null, null, 0f, 0f, 1f, 1f).isEmpty())+ assertTrue(OdfParser.parsePolyPoints(" ", null, 0f, 0f, 1f, 1f).isEmpty())+ // Zero viewBox dims fall back to 1.+ assertEquals(1, OdfParser.parsePolyPoints("1,1", listOf(0f, 0f, 0f, 0f), 0f, 0f, 10f, 10f).size)+ }++ @Test+ fun is_tag_helper() {+ val parser = OdfParser.newParser(+ """<r xmlns:draw="urn:x:drawing:1.0" xmlns:office="urn:x:office:1.0">""" ++ """<draw:page/><office:text/></r>"""+ )+ var e = parser.eventType+ while (!(e == XmlPullParser.START_TAG && parser.name == "page")) e = parser.next()+ assertTrue(isTag(e, parser, "page", "draw"))+ assertFalse(isTag(e, parser, "page", "office"))+ assertFalse(isTag(XmlPullParser.TEXT, parser, "page", "draw"))+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2StylesTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2StylesTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2StylesTest.ktnew file mode 100644index 0000000000..3dcdabfe63--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2StylesTest.kt@@ -0,0 +1,375 @@+package com.vayunmathur.office.odf++import androidx.compose.ui.text.style.TextAlign+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 2/4 (OdfParser*): style parsing, inheritance merging, list styles and gradients.+ */+class OdfParser2StylesTest {++ private val ns =+ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:xlink="http://www.w3.org/1999/xlink" """ ++ """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" """ ++ """xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" """ ++ """xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0" """ ++ """xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0">"""++ private fun stylesXml(inner: String) = ns + "<office:automatic-styles>$inner</office:automatic-styles></office:document>"++ private fun styleDef(+ name: String,+ parent: String? = null,+ dataStyle: String? = null,+ inner: String,+ ): String {+ val p = if (parent != null) """ style:parent-style-name="$parent"""" else ""+ val d = if (dataStyle != null) """ style:data-style-name="$dataStyle"""" else ""+ return """<style:style style:name="$name" style:family="paragraph"$p$d>$inner</style:style>"""+ }++ // --- Text properties ---++ @Test+ fun text_properties_parsed() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "T1",+ inner = """<style:text-properties fo:font-weight="bold" fo:font-style="italic" """ ++ """fo:font-size="14pt" fo:font-name="Arial" fo:color="#ff0000" """ ++ """fo:background-color="#00ff00" """ ++ """style:text-underline-style="solid" style:text-underline-color="#0000ff" """ ++ """style:text-line-through-style="solid" fo:letter-spacing="2pt" """ ++ """fo:text-transform="uppercase" fo:language="en" fo:country="US"/>""" ++ """<style:text-properties style:text-position="super 58%"/>"""+ )))+ val s = m["T1"]!!+ assertTrue(s.bold && s.italic)+ assertEquals(14f, s.fontSize ?: 0f)+ assertEquals("Arial", s.fontFamily)+ assertEquals(0xFFFF0000L, s.color)+ assertEquals(0xFF00FF00L, s.backgroundColor)+ assertTrue(s.underline)+ assertEquals("solid", s.underlineStyle)+ assertEquals(0xFF0000FFL, s.underlineColor)+ assertTrue(s.strikethrough)+ assertEquals(2f, s.letterSpacing ?: 0f)+ assertEquals("uppercase", s.textTransform)+ assertEquals("en", s.language)+ assertEquals("US", s.country)+ assertTrue(s.superscript)+ }++ @Test+ fun font_size_units_and_small_caps() {+ fun sizeOf(attr: String): Float? {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "T",+ inner = """<style:text-properties $attr/>"""+ )))+ return m["T"]!!.fontSize+ }+ assertEquals(12f, sizeOf("""fo:font-size="12px""""))+ assertEquals(6f, sizeOf("""fo:font-size="50%""""))+ // px@96 -> pt: 96px wide glyph at 96dpi = 1in = 72pt.+ assertEquals(72f, sizeOf("""fo:font-size="2.54cm"""") ?: 0f, 0.01f)+ assertEquals(24f, sizeOf("""fo:font-size="24""""))+ assertNull(sizeOf("""fo:font-size="huge""""))++ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "T",+ inner = """<style:text-properties fo:font-variant="small-caps"/>""" ++ """<style:text-properties style:text-position="sub 58%"/>"""+ )))+ assertEquals("uppercase", m["T"]!!.textTransform)+ assertTrue(m["T"]!!.subscript)+ }++ @Test+ fun text_position_shift_sign() {+ fun posOf(tp: String): Pair<Boolean, Boolean> {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "T",+ inner = """<style:text-properties style:text-position="$tp"/>"""+ )))+ return m["T"]!!.superscript to m["T"]!!.subscript+ }+ assertEquals(true to false, posOf("33% 58%"))+ assertEquals(false to true, posOf("-33% 58%"))+ assertEquals(false to false, posOf("0% 100%"))+ assertEquals(false to false, posOf("none"))+ }++ @Test+ fun font_family_fallback_and_transparent_background_ignored() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "T",+ inner = """<style:text-properties fo:font-family="Helvetica" fo:background-color="transparent" """ ++ """fo:letter-spacing="normal" fo:text-transform="none"/>"""+ )))+ val s = m["T"]!!+ assertEquals("Helvetica", s.fontFamily)+ assertNull(s.backgroundColor)+ assertNull(s.letterSpacing)+ assertNull(s.textTransform)+ }++ // --- Paragraph properties ---++ @Test+ fun paragraph_properties_parsed() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "P1",+ inner = """<style:paragraph-properties fo:text-align="justify" """ ++ """fo:margin-left="1cm" fo:margin-right="2cm" fo:margin-top="3mm" fo:margin-bottom="4mm" """ ++ """fo:text-indent="5mm" fo:padding="2mm" fo:background-color="#123456" """ ++ """fo:break-before="page" fo:break-after="page" fo:writing-mode="rl-tb" """ ++ """fo:line-height="150%" fo:keep-with-next="always" fo:keep-together="always" """ ++ """fo:widows="2" fo:orphans="3" fo:border="1pt solid #ff0000"/>"""+ )))+ val s = m["P1"]!!+ assertEquals(TextAlign.Justify, s.textAlign)+ assertEquals(37.8f, s.marginLeft, 0.01f)+ assertEquals(2 * 37.8f, s.marginRight, 0.01f)+ assertEquals(5 * 3.78f, s.textIndent ?: 0f, 0.01f)+ assertEquals(2 * 3.78f, s.padding, 0.01f)+ assertEquals(0xFF123456L, s.paragraphBackgroundColor)+ assertEquals("page", s.breakBefore)+ assertEquals("page", s.breakAfter)+ assertEquals("rl-tb", s.writingMode)+ assertEquals(1.5f, s.lineHeightPercent)+ assertTrue(s.keepWithNext && s.keepTogether)+ assertEquals(2, s.widows)+ assertEquals(3, s.orphans)+ assertEquals(0xFFFF0000L, s.paragraphBorderColor)+ assertNotNull(s.paraBorders)+ assertFalse(s.paraBorders!!.isEmpty())+ }++ @Test+ fun paragraph_align_values_and_padding_sides() {+ fun alignOf(a: String?): TextAlign? {+ val attr = if (a == null) "" else """ fo:text-align="$a""""+ val m = OdfParser.parseStyles(stylesXml(styleDef("P", inner = "<style:paragraph-properties$attr/>")))+ return m["P"]!!.textAlign+ }+ assertEquals(TextAlign.Start, alignOf("start"))+ assertEquals(TextAlign.Start, alignOf("left"))+ assertEquals(TextAlign.Center, alignOf("center"))+ assertEquals(TextAlign.End, alignOf("end"))+ assertEquals(TextAlign.End, alignOf("right"))+ assertEquals(TextAlign.Justify, alignOf("justify"))+ assertNull(alignOf("char"))+ assertNull(alignOf(null))++ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "P",+ inner = """<style:paragraph-properties fo:padding-left="3mm"/>"""+ )))+ assertEquals(3 * 3.78f, m["P"]!!.padding, 0.01f)+ }++ @Test+ fun tab_stops_and_drop_cap() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "P",+ inner = """<style:paragraph-properties><style:tab-stop style:position="2cm" """ ++ """style:type="right" style:leader-char="."/></style:paragraph-properties>""" ++ """<style:drop-cap style:lines="3" style:length="2"/>"""+ )))+ val s = m["P"]!!+ assertEquals(listOf(2 * 37.8f), s.tabStops)+ assertEquals(2 * 37.8f, s.tabStopDetails.single().position, 0.01f)+ assertEquals("right", s.tabStopDetails.single().type)+ assertEquals(".", s.tabStopDetails.single().leaderChar)+ assertEquals(3, s.dropCapLines)+ assertEquals(2, s.dropCapLength)+ }++ // --- Graphic / drawing-page / table properties ---++ @Test+ fun graphic_properties_parsed() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "G",+ inner = """<style:graphic-properties draw:fill="solid" draw:fill-color="#112233" """ ++ """draw:stroke="dash" draw:stroke-color="#445566" svg:stroke-width="2pt" """ ++ """draw:marker-start="Arrow" fo:clip="rect(1% 0% 0% 0%)" """ ++ """style:image-opacity="50%" draw:color-mode="greyscale"/>"""+ )))+ val s = m["G"]!!+ assertEquals(0xFF112233L, s.drawFillColor)+ assertTrue(s.strokeDashed)+ assertEquals(0xFF445566L, s.drawStrokeColor)+ assertTrue(s.markerStart)+ assertEquals("rect(1% 0% 0% 0%)", s.clip)+ assertEquals(50f, s.imageOpacity)+ assertEquals("greyscale", s.imageColorMode)+ }++ @Test+ fun gradient_fill_name_and_drawing_page_transition() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "G",+ inner = """<style:graphic-properties draw:fill="gradient" draw:fill-gradient-name="grad1"/>""" ++ """<style:drawing-page-properties draw:fill="solid" draw:fill-color="#abcdef" """ ++ """presentation:transition-style="dissolve" presentation:transition-speed="medium"/>"""+ )))+ val s = m["G"]!!+ assertEquals("grad1", s.fillGradientName)+ assertEquals(0xFFABCDEFL, s.drawFillColor)+ assertEquals("dissolve", s.transitionType)+ assertEquals("medium", s.transitionSpeed)+ }++ @Test+ fun table_cell_and_column_row_properties() {+ val m = OdfParser.parseStyles(stylesXml(+ styleDef(+ "C",+ inner = """<style:table-cell-properties fo:background-color="#aabbcc" """ ++ """fo:border="1pt solid #112233" fo:border-top="2pt dashed #445566" """ ++ """style:vertical-align="middle" fo:wrap-option="wrap"/>"""+ ) ++ styleDef("COL", inner = """<style:table-column-properties style:column-width="3cm"/>""") ++ styleDef("ROW", inner = """<style:table-row-properties style:row-height="1cm"/>""")+ ))+ val c = m["C"]!!+ assertEquals(0xFFAABBCCL, c.cellBackgroundColor)+ assertEquals(0xFF112233L, c.cellBorderColor)+ assertNotNull(c.cellBorders)+ assertEquals("middle", c.cellVerticalAlign)+ assertTrue(c.cellWrap)+ assertEquals(3 * 37.8f, m["COL"]!!.columnWidth ?: 0f, 0.01f)+ assertEquals(37.8f, m["ROW"]!!.rowHeight ?: 0f, 0.01f)+ }++ @Test+ fun conditional_map_and_columns_and_data_style() {+ val m = OdfParser.parseStyles(stylesXml(styleDef(+ "C",+ dataStyle = "N1",+ inner = """<style:table-cell-properties><style:map """ ++ """style:condition="cell-content()>5" style:apply-style-name="High"/></style:table-cell-properties>""" ++ """<style:columns fo:column-count="2"/>"""+ )))+ assertEquals(listOf("cell-content()>5" to "High"), m["C"]!!.conditionalMaps)+ assertEquals(2, m["C"]!!.columnCount)+ assertEquals("N1", m["C"]!!.dataStyleName)+ }++ // --- resolveStyle inheritance ---++ @Test+ fun resolve_style_merges_parent_chain() {+ val m = OdfParser.parseStyles(stylesXml(+ styleDef(+ "Parent",+ inner = """<style:text-properties fo:font-weight="bold" fo:font-size="10pt" fo:color="#111111" """ ++ """fo:text-transform="lowercase"/>""" ++ """<style:paragraph-properties fo:text-align="center" fo:margin-left="1cm" """ ++ """fo:keep-together="always" fo:padding="2mm"/>""" ++ """<style:graphic-properties draw:fill="solid" draw:fill-color="#222222"/>"""+ ) ++ styleDef("Child", parent = "Parent", inner = """<style:text-properties fo:font-style="italic"/>""")+ ))+ val s = OdfParser.resolveStyle("Child", m)+ assertTrue(s.bold && s.italic)+ assertEquals(10f, s.fontSize)+ assertEquals(0xFF111111L, s.color)+ assertEquals("lowercase", s.textTransform)+ assertEquals(TextAlign.Center, s.textAlign)+ assertEquals(37.8f, s.marginLeft, 0.01f)+ assertTrue(s.keepTogether)+ assertEquals(2 * 3.78f, s.padding, 0.01f)+ assertEquals(0xFF222222L, s.drawFillColor)+ }++ @Test+ fun resolve_style_unknown_name_returns_default() {+ val s = OdfParser.resolveStyle("Missing", emptyMap())+ assertFalse(s.bold)+ assertNull(s.color)+ assertNull(OdfParser.resolveStyle(null, emptyMap()).fontFamily)+ }++ // --- List styles ---++ @Test+ fun list_styles_number_bullet_image_outline() {+ val m = OdfParser.parseListStyles(stylesXml(+ """<text:list-style style:name="L1">""" ++ """<text:list-level-style-number text:level="1" text:num-format="1" """ ++ """text:num-prefix="[" text:num-suffix="]" text:start-value="4"/>""" ++ """<text:list-level-style-bullet text:level="2" text:bullet-char="•"/>""" ++ """<text:list-level-style-image text:level="3" xlink:href="Pictures/b.png"/>""" ++ """</text:list-style>""" ++ """<text:outline-style>""" ++ """<text:outline-level-style text:level="1" text:num-format="I" """ ++ """text:num-suffix="." text:start-value="2" text:display-levels="1"/>""" ++ """<text:outline-level-style text:level="2"/>""" ++ """</text:outline-style>"""+ ))+ val l1 = m["L1"]!!+ assertTrue(l1.anyNumbered)+ val n1 = l1.levelStyle(1)+ assertTrue(n1.numbered)+ assertEquals("[", n1.prefix)+ assertEquals("]", n1.suffix)+ assertEquals(4, n1.startValue)+ assertEquals("•", l1.levelStyle(2).bulletChar)+ assertEquals("Pictures/b.png", l1.levelStyle(3).bulletImagePath)+ // Nearest-level fallback for an undefined level.+ assertEquals("Pictures/b.png", l1.levelStyle(4).bulletImagePath)++ val outline = m["%outline%"]!!+ assertEquals("I", outline.levelStyle(1).numberFormat)+ assertEquals(2, outline.levelStyle(1).startValue)+ // Empty num-format means a bullet (unnumbered) level.+ assertFalse(outline.levelStyle(2).numbered)+ }++ @Test+ fun checkbox_bullet_detection() {+ val m = OdfParser.parseListStyles(stylesXml(+ """<text:list-style style:name="CB">""" ++ """<text:list-level-style-bullet text:level="1" text:bullet-char="☐"/>""" ++ """<text:list-level-style-bullet text:level="2" loext:checkbox="true"/>""" ++ """</text:list-style>"""+ ))+ assertTrue(m["CB"]!!.levelStyle(1).checkbox)+ assertTrue(m["CB"]!!.levelStyle(2).checkbox)+ assertFalse(m["CB"]!!.anyNumbered)+ }++ // --- Gradients ---++ @Test+ fun gradients_parsed_with_angle_kinds() {+ val m = OdfParser.parseGradients(+ ns ++ """<draw:gradient draw:name="g1" draw:start-color="#ff0000" draw:end-color="#0000ff" """ ++ """draw:angle="900" draw:style="linear"/>""" ++ """<draw:gradient draw:name="g2" draw:start-color="#000000" draw:end-color="#ffffff" """ ++ """draw:angle="45deg" draw:style="axial"/>""" ++ """<draw:gradient draw:name="bad" draw:start-color="#000000"/>""" ++ """</office:document>"""+ )+ assertEquals(2, m.size)+ assertEquals(0xFFFF0000L, m["g1"]!!.startColor)+ assertEquals(0xFF0000FFL, m["g1"]!!.endColor)+ assertEquals(90f, m["g1"]!!.angle, 0.001f)+ assertEquals("linear", m["g1"]!!.style)+ assertEquals(45f, m["g2"]!!.angle, 0.001f)+ }+}
office/src/test/java/com/vayunmathur/office/odf/OdfParser2TextTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfParser2TextTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2TextTest.ktnew file mode 100644index 0000000000..8acec83cab--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfParser2TextTest.kt@@ -0,0 +1,424 @@+package com.vayunmathur.office.odf++import androidx.compose.ui.text.style.TextAlign+import com.vayunmathur.library.ui.odf.ListType+import com.vayunmathur.library.ui.odf.OdfBookmark+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * Slice 2/4 (OdfParser*): text-document body parsing — headings, paragraphs, lists,+ * tables, sections, TOC, bookmarks, page breaks and tracked changes.+ */+class OdfParser2TextTest {++ private val head =+ """<?xml version="1.0" encoding="UTF-8"?>""" ++ """<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" """ ++ """xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" """ ++ """xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" """ ++ """xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" """ ++ """xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" """ ++ """xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" """ ++ """xmlns:dc="http://purl.org/dc/elements/1.1/">"""++ private val numListStyle =+ """<text:list-style style:name="L1">""" ++ """<text:list-level-style-number text:level="1" text:num-format="1" text:num-suffix="."/>""" ++ """</text:list-style>"""++ private val bulletListStyle =+ """<text:list-style style:name="LB">""" ++ """<text:list-level-style-bullet text:level="1" text:bullet-char="▪"/>""" ++ """</text:list-style>"""++ private fun doc(body: String, autoStyles: String = numListStyle): OdfDocument.TextDocument =+ OdfParser.parseTextXml(+ head ++ "<office:automatic-styles>$autoStyles</office:automatic-styles>" ++ "<office:body><office:text>$body</office:text></office:body></office:document>"+ )++ private fun paragraphs(d: OdfDocument.TextDocument) =+ d.content.mapNotNull { (it as? OdfContentBlock.Paragraph)?.paragraph }++ // --- Headings ---++ @Test+ fun heading_levels_map_to_styles() {+ val d = doc(+ """<text:h text:outline-level="1">One</text:h>""" ++ """<text:h text:outline-level="2">Two</text:h>""" ++ """<text:h text:outline-level="3">Three</text:h>""" ++ """<text:h text:outline-level="9">Nine</text:h>"""+ )+ val styles = paragraphs(d).map { it.style }+ assertEquals(+ listOf(ParagraphStyle.HEADING1, ParagraphStyle.HEADING2, ParagraphStyle.HEADING3, ParagraphStyle.HEADING4),+ styles+ )+ assertEquals(listOf("One", "Two", "Three", "Nine"), paragraphs(d).map { it.spans.single().text })+ }++ @Test+ fun heading_defaults_to_level_one_and_resolves_alignment() {+ val stylesXml =+ """<style:style style:name="HC" style:family="paragraph">""" ++ """<style:paragraph-properties fo:text-align="center"/>""" ++ """</style:style>"""+ val d = OdfParser.parseTextXml(+ head ++ "<office:automatic-styles>$stylesXml</office:automatic-styles>" ++ """<office:body><office:text><text:h text:style-name="HC">T</text:h></office:text></office:body></office:document>"""+ )+ val h = paragraphs(d).single()+ assertEquals(ParagraphStyle.HEADING1, h.style)+ assertEquals(TextAlign.Center, h.alignment)+ }++ @Test+ fun heading_page_breaks_emit_page_break_blocks() {+ val stylesXml =+ """<style:style style:name="PB" style:family="paragraph">""" ++ """<style:paragraph-properties fo:break-before="page" fo:break-after="page"/>""" ++ """</style:style>"""+ val d = OdfParser.parseTextXml(+ head ++ "<office:automatic-styles>$stylesXml</office:automatic-styles>" ++ """<office:body><office:text><text:h text:style-name="PB">T</text:h></office:text></office:body></office:document>"""+ )+ assertEquals(3, d.content.size)+ assertIs<OdfContentBlock.PageBreak>(d.content[0])+ assertIs<OdfContentBlock.Paragraph>(d.content[1])+ assertIs<OdfContentBlock.PageBreak>(d.content[2])+ }++ @Test+ fun heading_outline_numbering_two_levels() {+ val autoStyles =+ """<text:outline-style>""" ++ """<text:outline-level-style text:level="1" text:num-format="1" text:num-suffix="."/>""" ++ """<text:outline-level-style text:level="2" text:num-format="1" text:num-suffix="."/>""" ++ """</text:outline-style>"""+ val d = doc(+ """<text:h text:outline-level="1">A</text:h>""" ++ """<text:h text:outline-level="1">B</text:h>""" ++ """<text:h text:outline-level="2">C</text:h>""",+ autoStyles+ )+ val nums = paragraphs(d).map { it.outlineNumber }+ // Level 2 shows only its own counter (display-levels=1, i.e. "1." not "2.1.").+ assertEquals(listOf("1.", "2.", "1."), nums)+ }++ @Test+ fun heading_without_outline_style_has_no_number() {+ val d = doc("""<text:h text:outline-level="1">A</text:h>""", "")+ assertEquals(null, paragraphs(d).single().outlineNumber)+ }++ // --- Body paragraphs ---++ @Test+ fun plain_paragraphs_collected_with_styles() {+ val d = doc("""<text:p>first</text:p><text:p>second</text:p>""", "")+ assertEquals(listOf("first", "second"), paragraphs(d).map { it.spans.single().text })+ assertTrue(paragraphs(d).all { it.style == ParagraphStyle.BODY })+ }++ @Test+ fun empty_paragraph_outside_list_is_dropped() {+ val d = doc("""<text:p></text:p><text:p>kept</text:p>""", "")+ assertEquals(listOf("kept"), paragraphs(d).map { it.spans.single().text })+ }++ @Test+ fun body_page_break_style_emits_breaks() {+ val stylesXml =+ """<style:style style:name="BB" style:family="paragraph">""" ++ """<style:paragraph-properties fo:break-before="page"/>""" ++ """</style:style>"""+ val d = OdfParser.parseTextXml(+ head ++ "<office:automatic-styles>$stylesXml</office:automatic-styles>" ++ """<office:body><office:text><text:p text:style-name="BB">T</text:p></office:text></office:body></office:document>"""+ )+ assertIs<OdfContentBlock.PageBreak>(d.content.first())+ assertIs<OdfContentBlock.Paragraph>(d.content.last())+ }++ // --- Lists ---++ @Test+ fun nested_list_depth_tracked() {+ val d = doc(+ """<text:list text:style-name="L1">""" ++ """<text:list-item><text:p>a</text:p>""" ++ """<text:list text:style-name="L1"><text:list-item><text:p>b</text:p></text:list-item></text:list>""" ++ """</text:list-item></text:list>"""+ )+ val paras = paragraphs(d)+ assertEquals(2, paras.size)+ assertEquals(1, paras[0].listLevel)+ assertEquals(2, paras[1].listLevel)+ assertEquals(listOf(1, 1), paras.map { it.listItemIndex })+ }++ @Test+ fun list_start_value_and_item_start_value() {+ val autoStyles =+ """<text:list-style style:name="L9">""" ++ """<text:list-level-style-number text:level="1" text:num-format="1" text:start-value="5"/>""" ++ """</text:list-style>"""+ val d = doc(+ """<text:list text:style-name="L9">""" ++ """<text:list-item><text:p>a</text:p></text:list-item>""" ++ """<text:list-item text:start-value="9"><text:p>b</text:p></text:list-item>""" ++ """</text:list>""",+ autoStyles+ )+ assertEquals(listOf(5, 9), paragraphs(d).map { it.listItemIndex })+ }++ @Test+ fun bullet_list_type_and_checkbox_items() {+ val autoStyles = bulletListStyle ++ """<text:list-style style:name="LC">""" ++ """<text:list-level-style-bullet text:level="1" text:bullet-char="☐"/>""" ++ """</text:list-style>"""+ val d = doc(+ """<text:list text:style-name="LB"><text:list-item><text:p>a</text:p></text:list-item></text:list>""" ++ """<text:list text:style-name="LC">""" ++ """<text:list-item text:checkbox-status="checked"><text:p>b</text:p></text:list-item></text:list>""",+ autoStyles+ )+ val paras = paragraphs(d)+ assertEquals(ListType.BULLET, paras[0].listType)+ assertEquals("▪", paras[0].listBulletChar)+ assertEquals(ListType.CHECKBOX, paras[1].listType)+ assertTrue(paras[1].listChecked)+ }++ @Test+ fun continue_list_by_id_resumes_numbering() {+ val d = doc(+ """<text:list text:style-name="L1" xml:id="l1"><text:list-item><text:p>a</text:p></text:list-item></text:list>""" ++ """<text:list text:style-name="L1" text:continue-list="l1">""" ++ """<text:list-item><text:p>b</text:p></text:list-item></text:list>"""+ )+ assertEquals(listOf(1, 2), paragraphs(d).map { it.listItemIndex })+ }++ @Test+ fun list_number_format_and_affixes_exposed() {+ val autoStyles =+ """<text:list-style style:name="LP">""" ++ """<text:list-level-style-number text:level="1" text:num-format="a" """ ++ """text:num-prefix="(" text:num-suffix=")"/>""" ++ """</text:list-style>"""+ val d = doc(+ """<text:list text:style-name="LP"><text:list-item><text:p>a</text:p></text:list-item></text:list>""",+ autoStyles+ )+ val p = paragraphs(d).single()+ assertEquals("a", p.listNumberFormat)+ assertEquals("(", p.listNumberPrefix)+ assertEquals(")", p.listNumberSuffix)+ }++ // --- Sections / bookmarks / TOC ---++ @Test+ fun sections_emit_start_and_end() {+ val d = doc(+ """<text:section text:name="Intro"><text:p>x</text:p></text:section>""",+ ""+ )+ assertIs<OdfContentBlock.SectionStart>(d.content[0])+ assertEquals("Intro", (d.content[0] as OdfContentBlock.SectionStart).name)+ assertIs<OdfContentBlock.Paragraph>(d.content[1])+ assertIs<OdfContentBlock.SectionEnd>(d.content[2])+ }++ @Test+ fun bookmarks_recorded_with_content_index() {+ val d = doc(+ """<text:p>one</text:p><text:bookmark text:name="B1"/><text:p>two</text:p>""",+ ""+ )+ assertEquals(listOf(OdfBookmark("B1", 1)), d.bookmarks)+ assertEquals(2, paragraphs(d).size)+ }++ @Test+ fun toc_title_and_entries() {+ val d = doc(+ """<text:table-of-content>""" ++ """<text:index-body>""" ++ """<text:index-title><text:p>My TOC</text:p></text:index-title>""" ++ """<text:p>Chapter 1 .... 1</text:p>""" ++ """<text:p>Chapter 2 .... 3</text:p>""" ++ """</text:index-body></text:table-of-content>""",+ ""+ )+ val toc = d.content.filterIsInstance<OdfContentBlock.TableOfContents>().single()+ assertEquals("My TOC", toc.title)+ assertEquals(2, toc.entries.size)+ assertTrue(toc.entries[0].spans.single().text.startsWith("Chapter 1"))+ }++ @Test+ fun toc_default_title_when_no_index_title() {+ val d = doc(+ """<text:table-of-content><text:index-body><text:p>E1</text:p></text:index-body></text:table-of-content>""",+ ""+ )+ val toc = d.content.filterIsInstance<OdfContentBlock.TableOfContents>().single()+ assertEquals("Table of Contents", toc.title)+ assertEquals(1, toc.entries.size)+ }++ // --- Text tables ---++ @Test+ fun text_table_with_columns_rows_and_header() {+ val d = doc(+ """<table:table table:name="T">""" ++ """<table:table-column table:number-columns-repeated="2"/>""" ++ """<table:table-header-rows>""" ++ """<table:table-row><table:table-cell><text:p>H1</text:p></table:table-cell>""" ++ """<table:table-cell><text:p>H2</text:p></table:table-cell></table:table-row>""" ++ """</table:table-header-rows>""" ++ """<table:table-row><table:table-cell><text:p>A</text:p></table:table-cell>""" ++ """<table:table-cell table:number-columns-spanned="2"><text:p>B</text:p></table:table-cell></table:table-row>""" ++ """<table:table-row><table:covered-table-cell/></table:table-row>""" ++ """</table:table>""",+ ""+ )+ val table = d.content.filterIsInstance<OdfContentBlock.Table>().single().table+ assertEquals("T", table.name)+ assertEquals(2, table.columns.size)+ assertEquals(3, table.rows.size)+ assertEquals(1, table.headerRowCount)+ assertEquals("H1", table.rows[0].cells[0].paragraphs.single().spans.single().text)+ assertEquals(2, table.rows[1].cells[1].colSpan)+ assertTrue(table.rows[2].cells.single().isCovered)+ }++ @Test+ fun text_table_repeated_columns_capped() {+ val d = doc(+ """<table:table table:name="T">""" ++ """<table:table-column table:number-columns-repeated="5000"/>""" ++ """<table:table-row><table:table-cell><text:p>x</text:p></table:table-cell></table:table-row>""" ++ """</table:table>""",+ ""+ )+ val table = d.content.filterIsInstance<OdfContentBlock.Table>().single().table+ // MAX_REPEATED = 100 caps runaway repeats.+ assertEquals(100, table.columns.size)+ }++ @Test+ fun text_table_cell_formula_and_spans() {+ val d = doc(+ """<table:table table:name="T">""" ++ """<table:table-row><table:table-cell table:formula="of:=SUM([.A1])">""" ++ """<text:p>5</text:p><text:p>more</text:p></table:table-cell></table:table-row>""" ++ """</table:table>""",+ ""+ )+ val cell: OdfTableCell = d.content.filterIsInstance<OdfContentBlock.Table>().single().table.rows[0].cells[0]+ assertEquals("of:=SUM([.A1])", cell.formula)+ assertEquals(2, cell.paragraphs.size)+ }++ // --- Tracked changes ---++ private val changesBody =+ """<text:tracked-changes>""" ++ """<text:changed-region text:id="c1"><text:insertion><dc:creator>Alice</dc:creator><dc:date>2024-01-01</dc:date></text:insertion></text:changed-region>""" ++ """<text:changed-region text:id="c2"><text:deletion><text:p>gone <text:span>text</text:span></text:p></text:deletion></text:changed-region>""" ++ """<text:changed-region text:id="c3"><text:format-change/></text:changed-region>""" ++ """</text:tracked-changes>"""++ @Test+ fun tracked_changes_metadata_and_deletion_text() {+ val d = doc(changesBody + """<text:p>after</text:p>""", "")+ assertEquals(3, d.changes.size)+ assertEquals("insertion", d.changes[0].type)+ assertEquals("Alice", d.changes[0].author)+ assertEquals("2024-01-01", d.changes[0].date)+ assertEquals("deletion", d.changes[1].type)+ assertEquals("format-change", d.changes[2].type)+ assertEquals(1, paragraphs(d).size)+ }++ @Test+ fun insertion_range_marked_on_spans() {+ val d = doc(+ changesBody ++ """<text:p>before<text:change-start text:change-id="c1"/> new<text:change-end text:change-id="c1"/> tail</text:p>""",+ ""+ )+ val spans = paragraphs(d).single().spans+ val inserted = spans.filter { it.changeKind == "insertion" }+ assertEquals(1, inserted.size)+ assertEquals(" new", inserted.single().text)+ assertEquals("c1", inserted.single().changeId)+ assertFalse(spans.any { it.text == "before" && it.changeKind == "insertion" })+ }++ @Test+ fun deletion_point_expands_deleted_text() {+ val d = doc(+ changesBody + """<text:p>keep<text:change text:change-id="c2"/> end</text:p>""",+ ""+ )+ val spans = paragraphs(d).single().spans+ val deleted = spans.filter { it.changeKind == "deletion" }+ assertEquals(1, deleted.size)+ assertEquals("c2", deleted.single().changeId)+ assertTrue(deleted.single().text.contains("gone"))+ assertTrue(deleted.single().text.contains("text"))+ }++ @Test+ fun unknown_change_id_deletion_is_empty_span() {+ val d = doc("""<text:p>a<text:change text:change-id="nope"/>b</text:p>""", "")+ val deleted = paragraphs(d).single().spans.filter { it.changeKind == "deletion" }+ assertEquals(1, deleted.size)+ assertEquals("", deleted.single().text)+ }++ // --- Body inline media blocks ---++ @Test+ fun body_paragraph_frame_text_box_emits_paragraphs() {+ val d = doc(+ """<text:p><draw:frame draw:name="f" svg:width="2cm" svg:height="1cm" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0">""" ++ """<draw:text-box><text:p>boxed</text:p></draw:text-box></draw:frame></text:p>""",+ ""+ )+ assertTrue(paragraphs(d).any { it.spans.singleOrNull()?.text == "boxed" })+ }++ @Test+ fun text_doc_frame_with_text_box_emits_paragraphs() {+ val d = doc(+ """<draw:frame draw:name="f" svg:x="0" svg:y="0" svg:width="3cm" svg:height="2cm" """ ++ """xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0">""" ++ """<draw:text-box><text:p>framed</text:p></draw:text-box></draw:frame>""",+ ""+ )+ assertTrue(paragraphs(d).any { it.spans.singleOrNull()?.text == "framed" })+ }+}