Modern Apps git

← Modern-Apps.git

office: several rendering improvements

Commit
73f156ce5012b3af5939e593f6e92fd06bdfb381
Author
Vayun Mathur <[email protected]>
When
2026-07-28 19:43 UTC (4 months ago)
Parents
740247d

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocument.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocument.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocument.ktindex 6e3c9a23d0..23cdd730a1 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocument.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfDocument.kt@@ -460,7 +460,15 @@ sealed class OdfSlideElement { /** Geometry (x, y, width, height) of a floating element, in px@96. (Phase 1) */ fun OdfSlideElement.bounds(): FloatArray = when (this) {     is OdfSlideElement.Frame -> floatArrayOf(frame.x, frame.y, frame.width, frame.height)-    is OdfSlideElement.Shape -> floatArrayOf(shape.x, shape.y, shape.width, shape.height)+    is OdfSlideElement.Shape -> when (val s = shape) {+        // A line's (x,y) is its first endpoint, which may not be the top-left; position the+        // bounding box at the min corner so it isn't drawn off to one side.+        is OdfShape.Line -> floatArrayOf(+            minOf(s.x, s.x2), minOf(s.y, s.y2),+            kotlin.math.abs(s.x2 - s.x), kotlin.math.abs(s.y2 - s.y)+        )+        else -> floatArrayOf(s.x, s.y, s.width, s.height)+    } }  /** Returns a copy of the element repositioned/resized to the given bounds (px@96). (Phase 1) */@@ -486,7 +494,9 @@ data class OdfFrame(     val fillColor: Long? = null,     val strokeColor: Long? = null,     val strokeWidth: Float? = null,-    val fillGradient: OdfGradient? = null+    val fillGradient: OdfGradient? = null,+    /** Rotation in degrees clockwise (from the shape/frame transform). */+    val rotationDegrees: Float = 0f )  sealed class OdfShape {
office/src/main/java/com/vayunmathur/office/odf/DocumentImporter.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/DocumentImporter.kt b/office/src/main/java/com/vayunmathur/office/odf/DocumentImporter.ktindex f6060809ad..65874fc758 100644--- a/office/src/main/java/com/vayunmathur/office/odf/DocumentImporter.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/DocumentImporter.kt@@ -26,6 +26,10 @@ object DocumentImporter {             "pptx", "pptm", "potx", "potm", "ppsx", "ppsm" ->                 OoxmlImporter.import(readBytes(context, uri), fileName)                     ?: throw IllegalArgumentException("Unsupported or corrupt Office file")+            "doc", "xls", "ppt" -> throw IllegalArgumentException(+                "Legacy Microsoft Office 97-2003 files (.doc/.xls/.ppt) aren't supported. " ++                    "Open the file in Office or LibreOffice and save it as .docx/.xlsx/.pptx (or ODF)."+            )             "csv" -> OdfParser.parseCsv(readText(context, uri), fileName, ',')             "tsv", "tab" -> OdfParser.parseCsv(readText(context, uri), fileName, '\t')             "md", "markdown" -> MarkdownOdfConverter.markdownToOdf(readText(context, uri), fileName.substringBeforeLast('.'))@@ -39,6 +43,11 @@ object DocumentImporter {     /** Detects the format from the bytes when the extension is unknown/absent. */     private fun sniff(context: Context, uri: Uri, fileName: String): OdfDocument {         val bytes = readBytes(context, uri)+        // OLE/CFB compound file (legacy binary Office, or an encrypted OOXML container).+        if (OoxmlImporter.isEncryptedOfficeFile(bytes)) throw IllegalArgumentException(+            "This looks like a legacy or password-protected Office file. Save it as .docx/.xlsx/.pptx " ++                "(or ODF) without a password and try again."+        )         val isZip = bytes.size >= 2 && bytes[0] == 'P'.code.toByte() && bytes[1] == 'K'.code.toByte()         return when {             isZip && OoxmlImporter.looksLikeOoxml(bytes) ->
office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt b/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.ktindex c46ded1f95..4d7037b447 100644--- a/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt@@ -15,6 +15,62 @@ internal object ExcelFormula {             "(?![A-Za-z0-9_(])"     ) +    // A relative/absolute A1 cell reference (col letters + row), used by [shift].+    private val CELL = Regex(+        "(?<![A-Za-z0-9_$])" ++            "(\\$?)([A-Za-z]{1,3})(\\$?)([0-9]+)" ++            "(?![A-Za-z0-9_(])"+    )++    /**+     * Shifts the relative references in an Excel formula body by [dRow]/[dCol] (used to re-base a+     * shared formula from its master cell to a dependent cell). Absolute ($) parts and string+     * literals are left untouched.+     */+    fun shift(excel: String, dRow: Int, dCol: Int): String {+        if (dRow == 0 && dCol == 0) return excel+        val sb = StringBuilder()+        var i = 0+        while (i < excel.length) {+            val c = excel[i]+            if (c == '"') {+                var j = i + 1+                while (j < excel.length) {+                    if (excel[j] == '"') { if (j + 1 < excel.length && excel[j + 1] == '"') { j += 2; continue }; break }+                    j+++                }+                val end = if (j < excel.length) j else excel.length - 1+                sb.append(excel, i, minOf(end + 1, excel.length)); i = end + 1+            } else {+                val nextQuote = excel.indexOf('"', i).let { if (it < 0) excel.length else it }+                sb.append(shiftSegment(excel.substring(i, nextQuote), dRow, dCol))+                i = nextQuote+            }+        }+        return sb.toString()+    }++    private fun shiftSegment(seg: String, dRow: Int, dCol: Int): String = CELL.replace(seg) { m ->+        val colAbs = m.groupValues[1] == "$"+        val rowAbs = m.groupValues[3] == "$"+        val col = if (colAbs) m.groupValues[2] else indexToCol((colToIndex(m.groupValues[2]) + dCol).coerceAtLeast(0))+        val row = if (rowAbs) m.groupValues[4].toInt() else (m.groupValues[4].toInt() + dRow).coerceAtLeast(1)+        "${m.groupValues[1]}$col${m.groupValues[3]}$row"+    }++    private fun colToIndex(letters: String): Int {+        var n = 0+        for (c in letters) n = n * 26 + (c.uppercaseChar() - 'A' + 1)+        return n - 1+    }++    private fun indexToCol(index: Int): String {+        var n = index + 1+        val sb = StringBuilder()+        while (n > 0) { val rem = (n - 1) % 26; sb.insert(0, ('A' + rem)); n = (n - 1) / 26 }+        return sb.toString()+    }+     /** Returns an "of:=…" formula for the given Excel formula body (with or without a leading '='). */     fun toOdf(excel: String): String {         val body = excel.trim().removePrefix("=")@@ -23,7 +79,16 @@ internal object ExcelFormula {         while (i < body.length) {             val c = body[i]             if (c == '"') {-                val end = body.indexOf('"', i + 1).let { if (it < 0) body.length else it }+                // Scan to the closing quote, treating "" as an escaped quote inside the literal.+                var j = i + 1+                while (j < body.length) {+                    if (body[j] == '"') {+                        if (j + 1 < body.length && body[j + 1] == '"') { j += 2; continue }+                        break+                    }+                    j+++                }+                val end = if (j < body.length) j else body.length - 1                 sb.append(body, i, minOf(end + 1, body.length))                 i = end + 1             } else {@@ -54,6 +119,11 @@ internal object ExcelFormula {         }     } -    private fun prefixSheet(sheet: String): String =-        if (sheet.isEmpty()) "." else "\$${sheet.trim('\'')}."+    private fun prefixSheet(sheet: String): String {+        if (sheet.isEmpty()) return "."+        val name = sheet.trim('\'')+        // OpenFormula requires quoting sheet names with spaces/specials: [$'My Sheet'.A1].+        val needsQuote = sheet.startsWith("'") || !name.all { it.isLetterOrDigit() || it == '_' }+        return "\$" + (if (needsQuote) "'$name'" else name) + "."+    } }
office/src/main/java/com/vayunmathur/office/odf/ExcelNumFmt.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/ExcelNumFmt.kt b/office/src/main/java/com/vayunmathur/office/odf/ExcelNumFmt.ktindex e0eb4a2da6..5886cf2c16 100644--- a/office/src/main/java/com/vayunmathur/office/odf/ExcelNumFmt.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/ExcelNumFmt.kt@@ -22,7 +22,9 @@ internal object ExcelNumFmt {     )      fun forBuiltin(id: Int): OdfNumberFormat? {-        val code = BUILTINS[id] ?: if (id in 27..36 || id in 50..58) return parse("date") else return null+        // 27-36 and 50-58 are locale/CJK date-time builtins; use a sensible default date pattern+        // (the literal "date" is not a valid format code and yields garbage tokens).+        val code = BUILTINS[id] ?: if (id in 27..36 || id in 50..58) return parse("yyyy-mm-dd") else return null         if (code == "General") return null         return parse(code)     }@@ -42,13 +44,16 @@ internal object ExcelNumFmt {         // Strip color / condition brackets like [Red], [$-409], [>100] but keep [$...] currency payloads.         val currency = extractCurrency(section)         val cleaned = stripBrackets(section)+        // Date detection must ignore quoted literals: 0" days" is a number, not a date.+        val dateProbe = stripLiterals(section)          val isText = cleaned.contains("@")         val isScientific = cleaned.contains("E+", true) || cleaned.contains("E-", true)-        val hasDate = !isScientific && containsDateToken(cleaned)+        val hasDate = !isScientific && containsDateToken(dateProbe)         val isFraction = cleaned.contains("/") && Regex("[?#0]\\s*/\\s*[?#0]").containsMatchIn(cleaned) -        if (hasDate) return parseDateTime(cleaned)+        // Keep quotes for the token parser so literal segments aren't parsed as date letters.+        if (hasDate) return parseDateTime(stripBracketsKeepQuotes(section))          if (isText) return null @@ -97,15 +102,26 @@ internal object ExcelNumFmt {                 'd' -> { val run = runLen(code, i, 'd'); tokens.add(OdfNumberToken(if (run >= 3) "day-of-week" else "day", style = if (run == 4 || run == 2) "long" else "short", textual = run >= 3)); i += run }                 'h' -> { val run = runLen(code, i, 'h'); tokens.add(OdfNumberToken("hours", style = if (run >= 2) "long" else "short")); seenHour = true; seenTime = true; i += run }                 's' -> { val run = runLen(code, i, 's'); tokens.add(OdfNumberToken("seconds", style = if (run >= 2) "long" else "short")); seenTime = true; i += run }+                '"' -> {+                    // Quoted literal segment.+                    val end = code.indexOf('"', i + 1)+                    val lit = if (end >= 0) code.substring(i + 1, end) else code.substring(i + 1)+                    if (lit.isNotEmpty()) tokens.add(OdfNumberToken("text", text = lit))+                    i = if (end >= 0) end + 1 else code.length+                }+                '\\' -> {+                    // Backslash-escaped single literal char.+                    if (i + 1 < code.length) { tokens.add(OdfNumberToken("text", text = code[i + 1].toString())); i += 2 } else i+++                }                 else -> {                     if (code.startsWith("AM/PM", i, true)) { tokens.add(OdfNumberToken("am-pm")); i += 5 }                     else if (code.startsWith("A/P", i, true)) { tokens.add(OdfNumberToken("am-pm")); i += 3 }                     else {-                        // literal text run until next token char+                        // literal text run until next token char / quote / escape                         val start = i-                        while (i < code.length && code[i].lowercaseChar() !in "ymdhs" && !code.startsWith("AM/PM", i, true)) i+++                        while (i < code.length && code[i].lowercaseChar() !in "ymdhs" && code[i] != '"' && code[i] != '\\' && !code.startsWith("AM/PM", i, true)) i++                         val lit = code.substring(start, i)-                        if (lit.isNotEmpty()) tokens.add(OdfNumberToken("text", text = lit.replace("\\", "").trim('"').ifEmpty { lit }))+                        if (lit.isNotEmpty()) tokens.add(OdfNumberToken("text", text = lit))                     }                 }             }@@ -136,4 +152,12 @@ internal object ExcelNumFmt {      private fun stripBrackets(code: String): String =         code.replace(Regex("\\[[^]]*]"), "").replace("\"", "").replace("\\", "")++    /** Removes bracket sections but keeps quoted literals intact (for the date token parser). */+    private fun stripBracketsKeepQuotes(code: String): String =+        code.replace(Regex("\\[[^]]*]"), "")++    /** Removes bracket sections, quoted literals, and backslash escapes (for date detection). */+    private fun stripLiterals(code: String): String =+        code.replace(Regex("\\[[^]]*]"), "").replace(Regex("\"[^\"]*\""), "").replace(Regex("\\\\."), "") }
office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.ktindex b06842d2fb..d6ddf9ba21 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt@@ -53,6 +53,9 @@ object OdfFormulaEngine {     /** Formats a numeric value using an ODF number-format descriptor (H50). */     fun formatWithStyle(v: Double, fmt: OdfNumberFormat?): String {         if (fmt == null) return formatNumber(v)+        // Date / date-time: render the exact token pattern (falls back to ISO for a bare date flag).+        if (fmt.dateTimeTokens.isNotEmpty()) return formatDateTime(v, fmt.dateTimeTokens)+        if (fmt.isDate) return formatDateIso(v)         if (fmt.isTime) return formatTime(v)         if (fmt.isScientific) {             val decimals = (fmt.decimals ?: 2).coerceIn(0, 10)@@ -69,6 +72,55 @@ object OdfFormulaEngine {         return s     } +    private val MONTHS = arrayOf("January", "February", "March", "April", "May", "June",+        "July", "August", "September", "October", "November", "December")+    private val MONTHS_SHORT = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun",+        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")+    private val WEEKDAYS = arrayOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")+    private val WEEKDAYS_SHORT = arrayOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")++    /** Renders a date/time serial using an ordered [tokens] pattern (number:date-style children). */+    private fun formatDateTime(serial: Double, tokens: List<OdfNumberToken>): String {+        val cal = serialToCal(serial)+        val year = cal.get(GregorianCalendar.YEAR)+        val month = cal.get(GregorianCalendar.MONTH)                 // 0-based+        val day = cal.get(GregorianCalendar.DAY_OF_MONTH)+        val dow = cal.get(GregorianCalendar.DAY_OF_WEEK) - 1         // 0 = Sunday+        val hour24 = cal.get(GregorianCalendar.HOUR_OF_DAY)+        val minute = cal.get(GregorianCalendar.MINUTE)+        val second = cal.get(GregorianCalendar.SECOND)+        val ampm = tokens.any { it.kind == "am-pm" }+        val sb = StringBuilder()+        for (t in tokens) when (t.kind) {+            "year" -> sb.append(if (t.style == "long") year.toString() else (year % 100).toString().padStart(2, '0'))+            "month" -> sb.append(when {+                t.textual && t.style == "long" -> MONTHS[month]+                t.textual -> MONTHS_SHORT[month]+                t.style == "long" -> (month + 1).toString().padStart(2, '0')+                else -> (month + 1).toString()+            })+            "day" -> sb.append(if (t.style == "long") day.toString().padStart(2, '0') else day.toString())+            "day-of-week" -> sb.append(if (t.style == "long") WEEKDAYS[dow] else WEEKDAYS_SHORT[dow])+            "hours" -> {+                val h = if (ampm) (hour24 % 12).let { if (it == 0) 12 else it } else hour24+                sb.append(if (t.style == "long") h.toString().padStart(2, '0') else h.toString())+            }+            "minutes" -> sb.append(if (t.style == "long") minute.toString().padStart(2, '0') else minute.toString())+            "seconds" -> sb.append(if (t.style == "long") second.toString().padStart(2, '0') else second.toString())+            "am-pm" -> sb.append(if (hour24 < 12) "AM" else "PM")+            "text" -> sb.append(t.text ?: "")+        }+        return sb.toString()+    }++    /** Formats a date serial as ISO yyyy-MM-dd (fallback when no explicit tokens are present). */+    private fun formatDateIso(serial: Double): String {+        val cal = serialToCal(serial)+        return "%04d-%02d-%02d".format(+            cal.get(GregorianCalendar.YEAR), cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.DAY_OF_MONTH)+        )+    }+     /** Formats a day-fraction serial (0..1) as HH:MM:SS. */     private fun formatTime(serial: Double): String {         val totalSeconds = Math.round((serial - floor(serial)) * 86400.0)
office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfParser.ktindex 803743f974..ffe7f423d2 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt@@ -214,7 +214,10 @@ object OdfParser {      private fun parseColor(hex: String): Long? {         return try {-            val colorStr = hex.removePrefix("#")+            var colorStr = hex.trim().removePrefix("#")+            // Expand 3-digit shorthand (#FFF -> #FFFFFF).+            if (colorStr.length == 3) colorStr = colorStr.map { "$it$it" }.joinToString("")+            if (colorStr.length != 6) return null             0xFF000000L or colorStr.toLong(16)         } catch (_: Exception) { null }     }@@ -404,7 +407,16 @@ object OdfParser {                     "text-properties" -> {                         if (getAttr(parser, "font-weight") == "bold") bold = true                         if (getAttr(parser, "font-style") == "italic") italic = true-                        getAttr(parser, "font-size")?.let { s -> fontSize = s.replace("pt", "").replace("px", "").toFloatOrNull() }+                        getAttr(parser, "font-size")?.let { s ->+                            fontSize = when {+                                s.endsWith("pt") || s.endsWith("px") -> s.dropLast(2).toFloatOrNull()+                                // Percentage font sizes are relative to a 12pt default.+                                s.endsWith("%") -> s.dropLast(1).toFloatOrNull()?.let { it / 100f * 12f }+                                s.endsWith("cm") || s.endsWith("mm") || s.endsWith("in") || s.endsWith("pc") ->+                                    parseDimension(s).takeIf { it > 0f }?.let { it / (96f / 72f) } // px@96 -> pt+                                else -> s.toFloatOrNull()+                            }+                        }                         getAttr(parser, "font-name")?.let { fontFamily = it }                         if (fontFamily == null) getAttr(parser, "font-family")?.let { fontFamily = it }                         getAttr(parser, "text-underline-style")?.let { if (it != "none") { underline = true; underlineStyle = it } }@@ -418,9 +430,13 @@ object OdfParser {                         getAttr(parser, "color")?.let { color = parseColor(it) }                         getAttr(parser, "background-color")?.let { if (it != "transparent") bgColor = parseColor(it) }                         getAttr(parser, "text-position")?.let { tp ->+                            // Format is "<vertical-shift>% <height>%"; a 0% shift is baseline, not super/sub.+                            val shift = tp.substringBefore(' ').removeSuffix("%").trim().toFloatOrNull()                             when {-                                tp.startsWith("super") || (tp.contains("%") && !tp.startsWith("-")) -> superscript = true-                                tp.startsWith("sub") || tp.startsWith("-") -> subscript = true+                                tp.startsWith("super") -> superscript = true+                                tp.startsWith("sub") -> subscript = true+                                shift != null && shift > 0f -> superscript = true+                                shift != null && shift < 0f -> subscript = true                             }                         }                     }@@ -676,7 +692,8 @@ object OdfParser {                             numbered = true,                             numberFormat = getAttr(parser, "num-format")?.ifEmpty { "1" } ?: "1",                             prefix = getAttr(parser, "num-prefix") ?: "",-                            suffix = getAttr(parser, "num-suffix") ?: ".",+                            // ODF default for text:num-suffix is empty; only add "." when present.+                            suffix = getAttr(parser, "num-suffix") ?: "",                             startValue = getAttr(parser, "start-value")?.toIntOrNull() ?: 1                         )                     }@@ -1119,6 +1136,35 @@ object OdfParser {                         }                         spans.add(OdfSpan(text = "", refKind = parser.name, refName = getAttr(parser, "name")))                     }+                    "title", "desc" -> {+                        // svg:title/svg:desc inside a draw:frame are accessibility alt text (attach to+                        // the frame's image), NOT text fields. text:title remains a real field. Either way+                        // consume the whole subtree so its text never leaks into the paragraph. (alt-text fix)+                        val isSvg = parser.namespace?.contains("svg") == true+                        val isField = !isSvg && parser.name in FIELD_TAGS+                        if (textBuffer.isNotEmpty() && (isSvg || isField)) {+                            spans.add(makeSpan(textBuffer.toString(), currentStyleName, styles, currentHref))+                            textBuffer.clear()+                        }+                        val kind = parser.name+                        val d = parser.depth+                        val fb = StringBuilder()+                        var ev = parser.next()+                        while (!(ev == XmlPullParser.END_TAG && parser.depth == d)) {+                            if (ev == XmlPullParser.TEXT) fb.append(parser.text)+                            if (ev == XmlPullParser.END_DOCUMENT) break+                            ev = parser.next()+                        }+                        val t = fb.toString().trim()+                        when {+                            isSvg -> if (t.isNotEmpty() && imagesOut != null && imagesOut.isNotEmpty()) {+                                val idx = imagesOut.size - 1+                                imagesOut[idx] = if (kind == "title") imagesOut[idx].copy(altTitle = t)+                                    else imagesOut[idx].copy(altDesc = t)+                            }+                            isField -> spans.add(makeSpan(fb.toString(), currentStyleName, styles, currentHref).copy(field = kind))+                        }+                    }                     in FIELD_TAGS -> {                         // ODF text field elements -> a span carrying the field kind + cached value. (Priority 2)                         if (textBuffer.isNotEmpty()) {@@ -1401,7 +1447,9 @@ object OdfParser {                             else -> ListType.BULLET                         }                         listTypeStack.add(type)-                        listItemCounter.add(0)+                        // Honor text:start-value so numbered lists can begin at N (not always 1).+                        val startValue = styleInfo?.levelStyle(listDepth)?.startValue ?: 1+                        listItemCounter.add((startValue - 1).coerceAtLeast(0))                         listStyleStack.add(styleInfo)                     }                     inBody && parser.name == "list-item" -> {@@ -1489,16 +1537,21 @@ object OdfParser {                 "table-cell" -> {                     val colSpan = getAttr(parser, "number-columns-spanned")?.toIntOrNull() ?: 1                     val rowSpan = getAttr(parser, "number-rows-spanned")?.toIntOrNull() ?: 1+                    val repeated = getAttr(parser, "number-columns-repeated")?.toIntOrNull() ?: 1                     val styleName = getAttr(parser, "style-name")                     val resolved = resolveStyle(styleName, styles)-                    cells.add(OdfTableCell(-                        paragraphs = parseTableCellContent(parser, styles),-                        colSpan = colSpan, rowSpan = rowSpan,-                        backgroundColor = resolved.cellBackgroundColor,-                        borderColor = resolved.cellBorderColor,-                        formula = getAttr(parser, "formula"),-                        verticalAlign = resolved.cellVerticalAlign-                    ))+                    val formula = getAttr(parser, "formula")+                    val paragraphs = parseTableCellContent(parser, styles)+                    repeat(repeated.coerceAtMost(100)) {+                        cells.add(OdfTableCell(+                            paragraphs = paragraphs,+                            colSpan = colSpan, rowSpan = rowSpan,+                            backgroundColor = resolved.cellBackgroundColor,+                            borderColor = resolved.cellBorderColor,+                            formula = formula,+                            verticalAlign = resolved.cellVerticalAlign+                        ))+                    }                 }                 "covered-table-cell" -> {                     val repeated = getAttr(parser, "number-columns-repeated")?.toIntOrNull() ?: 1@@ -1880,6 +1933,17 @@ object OdfParser {             }             eventType = parser.next()         }+        // Drop trailing "filler" cells (spreadsheets pad each row out to 1024 columns via+        // number-columns-repeated on an empty, unstyled cell). Keeping them bloats the grid width.+        while (cells.isNotEmpty()) {+            val last = cells.last()+            val isFiller = last.text.isEmpty() && last.formula == null && !last.isCovered &&+                last.backgroundColor == null && last.borderColor == null &&+                last.borders?.isEmpty() != false && last.annotation == null &&+                last.numberValue == null && last.spannedColumns == 1 && last.rowSpan == 1 &&+                last.condFormats.isEmpty() && last.validationName == null && last.hyperlink == null+            if (isFiller) cells.removeAt(cells.size - 1) else break+        }         return cells     } @@ -1890,8 +1954,14 @@ object OdfParser {         val depth = parser.depth         var eventType = parser.next()         while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth)) {-            if (eventType == XmlPullParser.START_TAG && parser.name == "annotation") {-                annotation = parseAnnotation(parser, styles)+            if (eventType == XmlPullParser.START_TAG) when (parser.name) {+                "annotation" -> annotation = parseAnnotation(parser, styles)+                // Separate successive paragraphs within a cell with a line break.+                "p" -> if (sb.isNotEmpty()) sb.append("\n")+                // Whitespace-preserving inline elements (multi-space runs, tabs, line breaks).+                "s" -> sb.append(" ".repeat((getAttr(parser, "c")?.toIntOrNull() ?: 1).coerceIn(0, 4096)))+                "tab" -> sb.append("\t")+                "line-break" -> sb.append("\n")             } else if (eventType == XmlPullParser.TEXT) {                 sb.append(parser.text)             }@@ -2083,12 +2153,14 @@ object OdfParser {     // --- Shapes ---      private fun parseShape(parser: XmlPullParser, styles: Map<String, StyleInfo>, shapeName: String): OdfShape {-        val x = parseDimension(getAttr(parser, "x"))-        val y = parseDimension(getAttr(parser, "y"))-        val w = parseDimension(getAttr(parser, "width"))-        val h = parseDimension(getAttr(parser, "height"))-        val x2 = if (shapeName == "line") parseDimension(getAttr(parser, "x2")) else 0f-        val y2 = if (shapeName == "line") parseDimension(getAttr(parser, "y2")) else 0f+        // draw:line uses svg:x1/y1/x2/y2; all other shapes use svg:x/y/width/height.+        val isLine = shapeName == "line"+        val x = parseDimension(getAttr(parser, if (isLine) "x1" else "x"))+        val y = parseDimension(getAttr(parser, if (isLine) "y1" else "y"))+        val x2 = if (isLine) parseDimension(getAttr(parser, "x2")) else 0f+        val y2 = if (isLine) parseDimension(getAttr(parser, "y2")) else 0f+        val w = if (isLine) kotlin.math.abs(x2 - x) else parseDimension(getAttr(parser, "width"))+        val h = if (isLine) kotlin.math.abs(y2 - y) else parseDimension(getAttr(parser, "height"))         val polyPoints = if (shapeName == "polyline" || shapeName == "polygon") {             val vb = getAttr(parser, "viewBox")?.trim()?.split(Regex("\\s+"))?.mapNotNull { it.toFloatOrNull() }             parsePolyPoints(getAttr(parser, "points"), vb, x, y, w, h)
office/src/main/java/com/vayunmathur/office/odf/OoxmlChart.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlChart.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlChart.ktindex 1c2d8f1421..f314c00265 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlChart.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlChart.kt@@ -71,11 +71,15 @@ internal object OoxmlChart {         if (series.isEmpty() || series.all { it.vals.isEmpty() }) return null         if (type == ChartType.BAR && stacked) type = ChartType.STACKED_BAR -        val categories = series.maxByOrNull { it.cats.size }?.cats?.values?.toList() ?: emptyList()+        // Preserve idx alignment: densify by point index so a series missing a point (idx 0,1,3)+        // stays aligned with its categories instead of shifting later points left.+        val maxIdx = series.flatMap { it.cats.keys + it.vals.keys }.maxOrNull() ?: -1+        val catSource = series.maxByOrNull { it.cats.size }?.cats ?: sortedMapOf()+        val categories = (0..maxIdx).map { catSource[it] ?: "" }         val odfSeries = series.mapIndexed { i, s ->             OdfChartSeries(                 name = s.name ?: "Series ${i + 1}",-                values = s.vals.values.toList(),+                values = (0..maxIdx).map { s.vals[it] ?: 0f },                 color = s.color,                 dataLabels = s.dataLabels             )@@ -123,7 +127,8 @@ internal object OoxmlChart {                     }                 }                 "srgbClr", "schemeClr", "sysClr", "prstClr", "scrgbClr" ->-                    if (inSpPr && !inLn && s.color == null) s.color = OoxmlColor.parse(parser, theme)+                    // Capture the first color in spPr — for line/scatter series it lives inside <a:ln>.+                    if (inSpPr && s.color == null) s.color = OoxmlColor.parse(parser, theme)             } else if (e == XmlPullParser.END_TAG) when (parser.name) {                 "tx" -> { inTx = false; if (s.name == null && txt.isNotBlank()) s.name = txt.toString(); txt.clear() }                 "cat", "val", "xVal", "yVal" -> cache = null
office/src/main/java/com/vayunmathur/office/odf/OoxmlDocx.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlDocx.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlDocx.ktindex fdd4620d94..ad6f3037f4 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlDocx.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlDocx.kt@@ -31,14 +31,16 @@ internal object OoxmlDocx {         var highlight: Long? = null,         var shdFill: Long? = null,         var vanish: Boolean? = null,-        var lang: String? = null+        var lang: String? = null,+        var styleId: String? = null           // w:rStyle reference (character style)     ) {         /** Returns a new RPr with [o]'s non-null values overriding this one's. */         fun overlay(o: RPr) = RPr(             o.bold ?: bold, o.italic ?: italic, o.underline ?: underline, o.underlineColor ?: underlineColor,             o.strike ?: strike, o.color ?: color, o.sizeHalfPt ?: sizeHalfPt, o.font ?: font,             o.vertAlign ?: vertAlign, o.caps ?: caps, o.smallCaps ?: smallCaps, o.spacingTwips ?: spacingTwips,-            o.highlight ?: highlight, o.shdFill ?: shdFill, o.vanish ?: vanish, o.lang ?: lang+            o.highlight ?: highlight, o.shdFill ?: shdFill, o.vanish ?: vanish, o.lang ?: lang,+            o.styleId ?: styleId         )     } @@ -102,6 +104,14 @@ internal object OoxmlDocx {             return acc         } +        /** RPr contributed by a character style's basedOn chain only (no docDefaults). */+        fun charStyleRPr(id: String?): RPr {+            if (id == null) return RPr()+            var acc = RPr()+            for (s in chain(id)) acc = acc.overlay(s.rpr)+            return acc+        }+         fun resolvedPPr(id: String?): PPr {             if (id == null) return docDefaultPPr             pprCache[id]?.let { return it }@@ -202,7 +212,9 @@ internal object OoxmlDocx {         val extraImages: LinkedHashMap<String, ByteArray> = LinkedHashMap(),         val pendingBlocks: MutableList<OdfContentBlock> = mutableListOf(),         var pageSetup: OdfPageSetup? = null,-        var imageSeq: Int = 0+        var imageSeq: Int = 0,+        // Running list-item counters keyed by numId -> (ilvl -> count), for 1/2/3 numbering.+        val listCounters: HashMap<Int, HashMap<Int, Int>> = HashMap()     )      // ---- Body ----@@ -296,12 +308,14 @@ internal object OoxmlDocx {         }         val marginTop = eff.spacingBefore?.let { OoxmlUnits.twipsToPx(it) } ?: 0f         val marginBottom = eff.spacingAfter?.let { OoxmlUnits.twipsToPx(it) } ?: 0f-        val lineHeight = if (eff.lineRule == "auto" && eff.line != null) eff.line!! / 240f else null+        // Absent w:lineRule defaults to "auto" per the spec (line is then in 240ths = multiples).+        val lineHeight = if ((eff.lineRule == "auto" || eff.lineRule == null) && eff.line != null) eff.line!! / 240f else null          // Numbering         var listLevel = 0; var listType = ListType.BULLET         var numFmt = "1"; var bulletChar = "\u2022"; var prefix = ""; var suffix = "."         var isList = false+        var listItemIndex = 0         if (eff.numId != null && eff.numId != 0) {             val ilvl = eff.ilvl ?: 0             ctx.numbering.level(eff.numId!!, ilvl)?.let { lvl ->@@ -319,6 +333,12 @@ internal object OoxmlDocx {                         suffix = lvl.lvlText.substring(markers.last().range.last + 1)                     }                 }+                // Assign a running 1/2/3 index: increment this level, reset any deeper levels.+                val counters = ctx.listCounters.getOrPut(eff.numId!!) { HashMap() }+                val next = (counters[ilvl] ?: (lvl.start - 1)) + 1+                counters[ilvl] = next+                counters.keys.filter { it > ilvl }.toList().forEach { counters.remove(it) }+                listItemIndex = next             }         } @@ -334,6 +354,7 @@ internal object OoxmlDocx {             backgroundColor = eff.shdFill,             listLevel = listLevel,             listType = listType,+            listItemIndex = listItemIndex,             direction = direction,             lineHeightPercent = lineHeight,             borders = eff.borders?.takeIf { !it.isEmpty() },@@ -392,10 +413,11 @@ internal object OoxmlDocx {             e = parser.next()         } -        // Effective run props from paragraph mark + style default.+        // Effective run props: docDefaults+paragraph style < paragraph mark < character style < direct rPr.         val base = ctx.styles.resolvedRPr(ppr.styleId ?: ctx.styles.defaultParaStyle)         val paraMark = ppr.rPr ?: RPr()-        val eff = base.overlay(paraMark).overlay(rpr)+        val charStyle = ctx.styles.charStyleRPr(rpr.styleId)+        val eff = base.overlay(paraMark).overlay(charStyle).overlay(rpr)          if (eff.vanish == true) return         if (noteCitation != null) {@@ -544,6 +566,7 @@ internal object OoxmlDocx {         while (!(e == XmlPullParser.END_TAG && parser.depth == depth && (parser.name == "rPr" || parser.name == "defRPr"))) {             if (e == XmlPullParser.END_DOCUMENT) break             if (e == XmlPullParser.START_TAG) when (parser.name) {+                "rStyle" -> r.styleId = OoxmlXml.attr(parser, "val")                 "b" -> r.bold = OoxmlXml.boolAttr(OoxmlXml.attr(parser, "val"))                 "i" -> r.italic = OoxmlXml.boolAttr(OoxmlXml.attr(parser, "val"))                 "strike" -> r.strike = OoxmlXml.boolAttr(OoxmlXml.attr(parser, "val"))@@ -682,7 +705,8 @@ internal object OoxmlDocx {         val pt = szEighthPt / 8f         val color = OoxmlXml.attr(parser, "color")?.takeIf { !it.equals("auto", true) }?.let { "#$it" } ?: "#000000"         val odfStyle = when (style) { "single" -> "solid"; "double" -> "double"; "dotted" -> "dotted"; "dashed" -> "dashed"; else -> "solid" }-        return "%.2fpt %s %s".format(pt, odfStyle, color)+        // Force a dot decimal separator; a locale-formatted "0,50pt" is an invalid fo:border value.+        return "%.2fpt %s %s".format(java.util.Locale.ROOT, pt, odfStyle, color)     }      // ---- Styles / numbering parsing ----
office/src/main/java/com/vayunmathur/office/odf/OoxmlPackage.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlPackage.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlPackage.ktindex b21daef18a..f783c98b81 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlPackage.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlPackage.kt@@ -108,7 +108,9 @@ internal class OoxmlPackage(                             val ext = n.substringAfterLast('.', "").lowercase()                             when {                                 n.endsWith(".xml") || n.endsWith(".rels") ->-                                    entries[n] = zip.readBytes().toString(Charsets.UTF_8)+                                    // Strip a leading UTF-8 BOM (Word writes one on several parts);+                                    // a retained U+FEFF makes the pull parser reject the XML prolog.+                                    entries[n] = zip.readBytes().toString(Charsets.UTF_8).removePrefix("\uFEFF")                                 ext in MEDIA_EXTS -> media[n] = zip.readBytes()                             }                         }
office/src/main/java/com/vayunmathur/office/odf/OoxmlPptx.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlPptx.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlPptx.ktindex 625977e6ca..fcbac7fb09 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlPptx.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlPptx.kt@@ -63,12 +63,18 @@ internal object OoxmlPptx {         val part: String,         val theme: OoxmlTheme,         val rels: Map<String, OoxmlPackage.Rel>,+        val placeholders: PlaceholderMap = PlaceholderMap(emptyList(), emptyList()),         var autoY: Float = 36f     )      private fun parseSlide(pkg: OoxmlPackage, part: String, theme: OoxmlTheme, defaultName: String): OdfSlide {         val xml = pkg.entries[part] ?: return OdfSlide(defaultName)-        val ctx = SlideCtx(pkg, part, theme, pkg.relsFor(part))+        // Resolve the slide -> layout -> master chain for placeholder geometry + color map inheritance.+        val layoutPart = pkg.relsFor(part).values.firstOrNull { it.type?.endsWith("slideLayout") == true }?.target+        val masterPart = layoutPart?.let { pkg.relsFor(it).values.firstOrNull { r -> r.type?.endsWith("slideMaster") == true }?.target }+        val slideTheme = theme.withClrMap(parseClrMap(masterPart?.let { pkg.entries[it] }))+        val placeholders = PlaceholderMap(parsePlaceholderGeoms(pkg, layoutPart), parsePlaceholderGeoms(pkg, masterPart))+        val ctx = SlideCtx(pkg, part, slideTheme, pkg.relsFor(part), placeholders)         val parser = OoxmlXml.newParser(xml)         val elements = mutableListOf<OdfSlideElement>()         var bgColor: Long? = null@@ -85,7 +91,7 @@ internal object OoxmlPptx {                 "spTree" -> treeDepth = parser.depth                 "sp" -> if (parser.depth == treeDepth + 1) parseShape(parser, ctx)?.let { elements.add(it) }                 "pic" -> if (parser.depth == treeDepth + 1) parsePic(parser, ctx)?.let { elements.add(it) }-                "grpSp" -> if (parser.depth == treeDepth + 1) parseGroup(parser, ctx, 0f, 0f).let { elements.addAll(it) }+                "grpSp" -> if (parser.depth == treeDepth + 1) parseGroup(parser, ctx, null).let { elements.addAll(it) }                 "cxnSp" -> if (parser.depth == treeDepth + 1) parseConnector(parser, ctx)?.let { elements.add(it) }                 "graphicFrame" -> if (parser.depth == treeDepth + 1) parseGraphicFrame(parser, ctx)?.let { elements.add(it) }                 "transition" -> { transitionSpeed = OoxmlXml.attr(parser, "spd"); transitionType = readTransitionType(parser) }@@ -148,7 +154,9 @@ internal object OoxmlPptx {         var rot: Float = 0f, var flipH: Boolean = false, var flipV: Boolean = false,         var geom: String? = null, var fill: Long? = null, var gradient: OdfGradient? = null,         var stroke: Long? = null, var strokeWidth: Float? = null, var strokeDashed: Boolean = false,-        var cornerRadius: Float = 0f+        var cornerRadius: Float = 0f,+        // Placeholder identity (from <p:ph>), for inheriting geometry from the layout/master.+        var isPlaceholder: Boolean = false, var phType: String? = null, var phIdx: String? = null     )      private fun parseShape(parser: XmlPullParser, ctx: SlideCtx): OdfSlideElement? {@@ -160,6 +168,7 @@ internal object OoxmlPptx {         while (!(e == XmlPullParser.END_TAG && parser.depth == depth && parser.name == "sp")) {             if (e == XmlPullParser.END_DOCUMENT) break             if (e == XmlPullParser.START_TAG) when (parser.name) {+                "ph" -> { sp.isPlaceholder = true; sp.phType = OoxmlXml.attr(parser, "type"); sp.phIdx = OoxmlXml.attr(parser, "idx") }                 "spPr" -> parseSpPr(parser, ctx, sp)                 "txBody" -> { parseTxBody(parser, ctx, paras); if (paras.any { p -> p.spans.any { it.text.isNotBlank() } }) hasText = true }             }@@ -176,32 +185,111 @@ internal object OoxmlPptx {         if (hasText || geom == null || geom == "rect" || geom == "textBox") {             return OdfSlideElement.Frame(OdfFrame(                 x = x, y = y, width = w, height = h.coerceAtLeast(20f), paragraphs = paras.ifEmpty { listOf(OdfParagraph(listOf(OdfSpan("")))) },-                fillColor = sp.fill, strokeColor = sp.stroke, strokeWidth = sp.strokeWidth, fillGradient = sp.gradient+                fillColor = sp.fill, strokeColor = sp.stroke, strokeWidth = sp.strokeWidth, fillGradient = sp.gradient,+                rotationDegrees = sp.rot             ))         }         val shape = when (geom) {             "ellipse", "circle" -> OdfShape.Ellipse(x, y, w, h, sp.fill, sp.stroke, sp.strokeWidth, paras, sp.rot, sp.gradient, sp.strokeDashed)             "roundRect" -> OdfShape.Rect(x, y, w, h, sp.fill, sp.stroke, sp.strokeWidth, paras, cornerRadius = if (sp.cornerRadius > 0) sp.cornerRadius else minOf(w, h) * 0.15f, rotationDegrees = sp.rot, fillGradient = sp.gradient, strokeDashed = sp.strokeDashed)-            "line", "straightConnector1" -> OdfShape.Line(x, y, w, h, sp.fill, sp.stroke, sp.strokeWidth, paras, x2 = x + w, y2 = y + h, rotationDegrees = sp.rot, strokeDashed = sp.strokeDashed)+            "line", "straightConnector1" -> {+                // Honor flipH/flipV so a flipped diagonal points the right way.+                val x1 = if (sp.flipH) x + w else x; val ex = if (sp.flipH) x else x + w+                val y1 = if (sp.flipV) y + h else y; val ey = if (sp.flipV) y else y + h+                OdfShape.Line(x1, y1, w, h, sp.fill, sp.stroke, sp.strokeWidth, paras, x2 = ex, y2 = ey, rotationDegrees = sp.rot, strokeDashed = sp.strokeDashed)+            }             else -> OdfShape.CustomShape(x, y, w, h, sp.fill, sp.stroke, sp.strokeWidth, paras, sp.rot, sp.gradient, sp.strokeDashed)         }         return OdfSlideElement.Shape(shape)     }      private fun applyAutoGeometry(sp: SpProps, ctx: SlideCtx) {+        // A placeholder without its own xfrm inherits geometry from the layout/master.+        if (!sp.hasXfrm && sp.isPlaceholder) {+            ctx.placeholders.geom(sp.phType, sp.phIdx)?.let { g ->+                sp.x = g[0]; sp.y = g[1]; sp.w = g[2]; sp.h = g[3]; sp.hasXfrm = true+            }+        }         if (!sp.hasXfrm) {             sp.x = 36f; sp.w = 640f; sp.y = ctx.autoY; if (sp.h <= 0f) sp.h = 80f         }         ctx.autoY = sp.y + sp.h + 12f     } +    // ---- Placeholder inheritance (layout / master) ----++    private class PlaceholderInfo(val type: String?, val idx: String?, val x: Float, val y: Float, val w: Float, val h: Float)++    private class PlaceholderMap(private val layout: List<PlaceholderInfo>, private val master: List<PlaceholderInfo>) {+        /** Geometry [x,y,w,h] for a placeholder: idx match first, then type; layout overrides master. */+        fun geom(type: String?, idx: String?): FloatArray? =+            match(layout, type, idx) ?: match(master, type, idx)++        private fun match(list: List<PlaceholderInfo>, type: String?, idx: String?): FloatArray? {+            if (idx != null) list.firstOrNull { it.idx == idx }?.let { return floatArrayOf(it.x, it.y, it.w, it.h) }+            val t = normType(type)+            list.firstOrNull { normType(it.type) == t }?.let { return floatArrayOf(it.x, it.y, it.w, it.h) }+            return null+        }++        private fun normType(t: String?): String = when (t) { null -> "body"; "ctrTitle" -> "title"; else -> t }+    }++    /** Extracts placeholder geometries (with an explicit xfrm) from a layout/master part's spTree. */+    private fun parsePlaceholderGeoms(pkg: OoxmlPackage, part: String?): List<PlaceholderInfo> {+        val xml = part?.let { pkg.entries[it] } ?: return emptyList()+        val parser = OoxmlXml.newParser(xml)+        val list = mutableListOf<PlaceholderInfo>()+        var spDepth = -1+        var phType: String? = null; var phIdx: String? = null+        var x = 0f; var y = 0f; var w = 0f; var h = 0f; var hasXfrm = false; var inXfrm = false+        var e = parser.eventType+        while (e != XmlPullParser.END_DOCUMENT) {+            if (e == XmlPullParser.START_TAG) when (parser.name) {+                "sp" -> { spDepth = parser.depth; phType = null; phIdx = null; x = 0f; y = 0f; w = 0f; h = 0f; hasXfrm = false }+                "ph" -> if (spDepth >= 0) { phType = OoxmlXml.attr(parser, "type"); phIdx = OoxmlXml.attr(parser, "idx") }+                "xfrm" -> if (spDepth >= 0) inXfrm = true+                "off" -> if (inXfrm) { OoxmlXml.attr(parser, "x")?.toLongOrNull()?.let { x = OoxmlUnits.emuToPx(it) }; OoxmlXml.attr(parser, "y")?.toLongOrNull()?.let { y = OoxmlUnits.emuToPx(it) }; hasXfrm = true }+                "ext" -> if (inXfrm) { OoxmlXml.attr(parser, "cx")?.toLongOrNull()?.let { w = OoxmlUnits.emuToPx(it) }; OoxmlXml.attr(parser, "cy")?.toLongOrNull()?.let { h = OoxmlUnits.emuToPx(it) } }+            } else if (e == XmlPullParser.END_TAG) when (parser.name) {+                "xfrm" -> inXfrm = false+                "sp" -> if (parser.depth == spDepth) {+                    if (hasXfrm && (phType != null || phIdx != null)) list.add(PlaceholderInfo(phType, phIdx, x, y, w, h))+                    spDepth = -1+                }+            }+            e = parser.next()+        }+        return list+    }++    /** Parses a slide master's <p:clrMap> (bg1/tx1/... -> theme slot) attributes. */+    private fun parseClrMap(masterXml: String?): Map<String, String> {+        if (masterXml == null) return emptyMap()+        val parser = OoxmlXml.newParser(masterXml)+        var e = parser.eventType+        while (e != XmlPullParser.END_DOCUMENT) {+            if (e == XmlPullParser.START_TAG && parser.name == "clrMap") {+                val m = HashMap<String, String>()+                for (k in listOf("bg1", "tx1", "bg2", "tx2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink")) {+                    OoxmlXml.attr(parser, k)?.let { m[k.lowercase()] = it.lowercase() }+                }+                return m+            }+            e = parser.next()+        }+        return emptyMap()+    }+     private fun parseSpPr(parser: XmlPullParser, ctx: SlideCtx, sp: SpProps) {         val depth = parser.depth         var inLn = false+        var inEffect = false         var e = parser.next()         while (!(e == XmlPullParser.END_TAG && parser.depth == depth && parser.name == "spPr")) {             if (e == XmlPullParser.END_DOCUMENT) break             if (e == XmlPullParser.START_TAG) when (parser.name) {+                "effectLst", "effectDag" -> inEffect = true                 "xfrm" -> {                     sp.hasXfrm = true                     OoxmlXml.attr(parser, "rot")?.toIntOrNull()?.let { sp.rot = OoxmlUnits.angle60000ToDeg(it) }@@ -213,13 +301,17 @@ internal object OoxmlPptx {                 "prstGeom" -> sp.geom = OoxmlXml.attr(parser, "prst")                 "ln" -> { inLn = true; OoxmlXml.attr(parser, "w")?.toLongOrNull()?.let { sp.strokeWidth = OoxmlUnits.emuToPx(it) } }                 "prstDash" -> if (inLn) sp.strokeDashed = OoxmlXml.attr(parser, "val")?.contains("dash", true) == true-                "gradFill" -> sp.gradient = parseGradient(parser, ctx.theme)+                "gradFill" -> { val g = parseGradient(parser, ctx.theme); if (!inLn && !inEffect) sp.gradient = g }                 "srgbClr", "schemeClr", "sysClr", "prstClr", "scrgbClr" -> {                     val c = OoxmlColor.parse(parser, ctx.theme)-                    if (inLn) { if (sp.stroke == null) sp.stroke = c } else if (sp.fill == null) sp.fill = c+                    // Skip colors inside <a:effectLst> (e.g. shadow color) so they don't become the fill.+                    if (inLn) { if (sp.stroke == null) sp.stroke = c } else if (!inEffect && sp.fill == null) sp.fill = c                 }                 "noFill" -> if (!inLn) sp.fill = null-            } else if (e == XmlPullParser.END_TAG && parser.name == "ln") inLn = false+            } else if (e == XmlPullParser.END_TAG) when (parser.name) {+                "ln" -> inLn = false+                "effectLst", "effectDag" -> inEffect = false+            }             e = parser.next()         }     }@@ -267,6 +359,7 @@ internal object OoxmlPptx {         while (!(e == XmlPullParser.END_TAG && parser.depth == depth && parser.name == "pic")) {             if (e == XmlPullParser.END_DOCUMENT) break             if (e == XmlPullParser.START_TAG) when (parser.name) {+                "ph" -> { sp.isPlaceholder = true; sp.phType = OoxmlXml.attr(parser, "type"); sp.phIdx = OoxmlXml.attr(parser, "idx") }                 "spPr" -> parseSpPr(parser, ctx, sp)                 "cNvPr" -> desc = OoxmlXml.attr(parser, "descr") ?: OoxmlXml.attr(parser, "name")                 "blip" -> embed = OoxmlXml.attrNs(parser, RELS_NS, "embed") ?: OoxmlXml.attr(parser, "embed")@@ -293,27 +386,66 @@ internal object OoxmlPptx {      // ---- Groups / connectors ---- -    private fun parseGroup(parser: XmlPullParser, ctx: SlideCtx, dx: Float, dy: Float): List<OdfSlideElement> {+    /** Affine map (per-axis scale + offset) from a group's child coordinate space to screen px@96. */+    private class GroupTf(val ax: Float, val bx: Float, val ay: Float, val by: Float) {+        fun apply(x: Float, y: Float, w: Float, h: Float) = floatArrayOf(ax * x + bx, ay * y + by, w * ax, h * ay)+        companion object {+            /** parent ∘ child: apply child first (its space -> parent's child space), then parent. */+            fun compose(p: GroupTf, c: GroupTf) =+                GroupTf(p.ax * c.ax, p.ax * c.bx + p.bx, p.ay * c.ay, p.ay * c.by + p.by)+        }+    }++    private fun parseGroup(parser: XmlPullParser, ctx: SlideCtx, parentTf: GroupTf?): List<OdfSlideElement> {         val depth = parser.depth         val out = mutableListOf<OdfSlideElement>()+        var tf = parentTf         var e = parser.next()         while (!(e == XmlPullParser.END_TAG && parser.depth == depth && parser.name == "grpSp")) {             if (e == XmlPullParser.END_DOCUMENT) break             if (e == XmlPullParser.START_TAG) when (parser.name) {-                "sp" -> parseShape(parser, ctx)?.let { out.add(translate(it, dx, dy)) }-                "pic" -> parsePic(parser, ctx)?.let { out.add(translate(it, dx, dy)) }-                "cxnSp" -> parseConnector(parser, ctx)?.let { out.add(translate(it, dx, dy)) }-                "grpSp" -> out.addAll(parseGroup(parser, ctx, dx, dy))+                // grpSpPr precedes the children; fold the group's own off/ext/chOff/chExt into the transform.+                "grpSpPr" -> parseGroupXfrm(parser)?.let { own -> tf = parentTf?.let { GroupTf.compose(it, own) } ?: own }+                "sp" -> parseShape(parser, ctx)?.let { out.add(applyTf(it, tf)) }+                "pic" -> parsePic(parser, ctx)?.let { out.add(applyTf(it, tf)) }+                "cxnSp" -> parseConnector(parser, ctx)?.let { out.add(applyTf(it, tf)) }+                "grpSp" -> out.addAll(parseGroup(parser, ctx, tf))             }             e = parser.next()         }         return out     } -    private fun translate(el: OdfSlideElement, dx: Float, dy: Float): OdfSlideElement {-        if (dx == 0f && dy == 0f) return el+    /** Reads a group's <a:xfrm> (off/ext/chOff/chExt) into a child-space -> parent-space transform. */+    private fun parseGroupXfrm(parser: XmlPullParser): GroupTf? {+        val depth = parser.depth+        var offX = 0f; var offY = 0f; var extX = 0f; var extY = 0f+        var chOffX = 0f; var chOffY = 0f; var chExtX = 0f; var chExtY = 0f+        var inXfrm = false; var seen = false+        fun emu(a: String) = OoxmlXml.attr(parser, a)?.toLongOrNull()?.let { OoxmlUnits.emuToPx(it) } ?: 0f+        var e = parser.next()+        while (!(e == XmlPullParser.END_TAG && parser.depth == depth && parser.name == "grpSpPr")) {+            if (e == XmlPullParser.END_DOCUMENT) break+            if (e == XmlPullParser.START_TAG) when (parser.name) {+                "xfrm" -> { inXfrm = true; seen = true }+                "off" -> if (inXfrm) { offX = emu("x"); offY = emu("y") }+                "ext" -> if (inXfrm) { extX = emu("cx"); extY = emu("cy") }+                "chOff" -> if (inXfrm) { chOffX = emu("x"); chOffY = emu("y") }+                "chExt" -> if (inXfrm) { chExtX = emu("cx"); chExtY = emu("cy") }+            } else if (e == XmlPullParser.END_TAG && parser.name == "xfrm") inXfrm = false+            e = parser.next()+        }+        if (!seen) return null+        val ax = if (chExtX != 0f) extX / chExtX else 1f+        val ay = if (chExtY != 0f) extY / chExtY else 1f+        return GroupTf(ax, offX - chOffX * ax, ay, offY - chOffY * ay)+    }++    private fun applyTf(el: OdfSlideElement, tf: GroupTf?): OdfSlideElement {+        if (tf == null) return el         val b = el.bounds()-        return setElementBounds(el, b[0] + dx, b[1] + dy, b[2], b[3])+        val n = tf.apply(b[0], b[1], b[2], b[3])+        return setElementBounds(el, n[0], n[1], n[2], n[3])     }      private fun parseConnector(parser: XmlPullParser, ctx: SlideCtx): OdfSlideElement? {@@ -397,6 +529,7 @@ internal object OoxmlPptx {     // ---- Text ----      private fun parseTxBody(parser: XmlPullParser, ctx: SlideCtx, out: MutableList<OdfParagraph>) {+        val start = out.size         val depth = parser.depth         val endTag = parser.name  // txBody or txbx         var e = parser.next()@@ -405,6 +538,19 @@ internal object OoxmlPptx {             if (e == XmlPullParser.START_TAG && parser.name == "p") parseDrawingParagraph(parser, ctx)?.let { out.add(it) }             e = parser.next()         }+        // Assign running 1/2/3 numbering to contiguous numbered (buAutoNum) items per level.+        val counters = HashMap<Int, Int>()+        for (i in start until out.size) {+            val p = out[i]+            if (p.listType == ListType.NUMBERED) {+                val n = (counters[p.listLevel] ?: 0) + 1+                counters[p.listLevel] = n+                counters.keys.filter { it > p.listLevel }.toList().forEach { counters.remove(it) }+                out[i] = p.copy(listItemIndex = n)+            } else {+                counters.keys.filter { it >= p.listLevel }.toList().forEach { counters.remove(it) }+            }+        }     }      private fun parseDrawingParagraph(parser: XmlPullParser, ctx: SlideCtx): OdfParagraph? {
office/src/main/java/com/vayunmathur/office/odf/OoxmlTheme.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlTheme.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlTheme.ktindex 05a97f6048..00b3d0f83a 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlTheme.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlTheme.kt@@ -9,24 +9,30 @@ import org.xmlpull.v1.XmlPullParser internal class OoxmlTheme(     val colors: Map<String, Long>,     val majorFont: String?,-    val minorFont: String?+    val minorFont: String?,+    // Slide-master color map (bg1/tx1/bg2/tx2/accent* -> a theme slot dk1/lt1/...). Empty = defaults.+    val clrMap: Map<String, String> = emptyMap() ) {     /**      * Resolves a scheme color name (as it appears in `a:schemeClr val`, incl. tx1/bg1/tx2/bg2      * aliases and dk1/lt1/...) to an 0xFFRRGGBB base, or null. `phClr` returns null (context color).      */     fun schemeColor(name: String?): Long? {-        val key = when (name?.lowercase()) {-            "tx1", "dk1" -> "dk1"-            "bg1", "lt1" -> "lt1"-            "tx2", "dk2" -> "dk2"-            "bg2", "lt2" -> "lt2"-            null, "phclr" -> return null-            else -> name.lowercase()+        val lc = name?.lowercase() ?: return null+        if (lc == "phclr") return null+        // Apply the slide master's <p:clrMap> for the placeholder aliases (can invert on dark templates);+        // fall back to the standard tx1->dk1 / bg1->lt1 mapping when no map is present.+        val key = clrMap[lc] ?: when (lc) {+            "tx1" -> "dk1"; "bg1" -> "lt1"; "tx2" -> "dk2"; "bg2" -> "lt2"+            else -> lc         }         return colors[key]     } +    /** Returns a copy of this theme with the given slide-master color map applied. */+    fun withClrMap(map: Map<String, String>): OoxmlTheme =+        if (map.isEmpty()) this else OoxmlTheme(colors, majorFont, minorFont, map)+     companion object {         val DEFAULT = OoxmlTheme(             colors = mapOf(
office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.ktindex a44c111c87..65d2f1ec8a 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt@@ -103,9 +103,16 @@ internal object OoxmlXlsx {             if (e == XmlPullParser.START_TAG && parser.name == "si") {                 val depth = parser.depth                 val sb = StringBuilder()+                var phoneticDepth = -1                 var ev = parser.next()                 while (!(ev == XmlPullParser.END_TAG && parser.depth == depth && parser.name == "si")) {-                    if (ev == XmlPullParser.START_TAG && parser.name == "t") sb.append(OoxmlXml.readElementText(parser, "t"))+                    when {+                        // Skip <t> inside <rPh> phonetic-guide runs (furigana), which aren't visible text.+                        ev == XmlPullParser.START_TAG && parser.name == "rPh" -> phoneticDepth = parser.depth+                        ev == XmlPullParser.END_TAG && parser.name == "rPh" -> phoneticDepth = -1+                        ev == XmlPullParser.START_TAG && parser.name == "t" && phoneticDepth < 0 ->+                            sb.append(OoxmlXml.readElementText(parser, "t"))+                    }                     if (ev == XmlPullParser.END_DOCUMENT) break                     ev = parser.next()                 }@@ -288,9 +295,31 @@ internal object OoxmlXlsx {             val tint = OoxmlXml.attr(parser, "tint")?.toDoubleOrNull() ?: 0.0             return applyExcelTint(base, tint)         }+        OoxmlXml.attr(parser, "indexed")?.toIntOrNull()?.let { return indexedColor(it) }         return null     } +    /** Resolves a legacy indexed color (BIFF8 default palette) to 0xFFRRGGBB. */+    private fun indexedColor(idx: Int): Long? {+        val rgb = INDEXED_PALETTE.getOrNull(idx) ?: when (idx) {+            64 -> 0x000000L   // system foreground+            65 -> 0xFFFFFFL   // system background+            else -> return null+        }+        return 0xFF000000L or rgb+    }++    private val INDEXED_PALETTE = longArrayOf(+        0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,+        0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,+        0x800000, 0x008000, 0x000080, 0x808000, 0x800080, 0x008080, 0xC0C0C0, 0x808080,+        0x9999FF, 0x993366, 0xFFFFCC, 0xCCFFFF, 0x660066, 0xFF8080, 0x0066CC, 0xCCCCFF,+        0x000080, 0xFF00FF, 0xFFFF00, 0x00FFFF, 0x800080, 0x800000, 0x008080, 0x0000FF,+        0x00CCFF, 0xCCFFFF, 0xCCFFCC, 0xFFFF99, 0x99CCFF, 0xFF99CC, 0xCC99FF, 0xFFCC99,+        0x3366FF, 0x33CCCC, 0x99CC00, 0xFFCC00, 0xFF9900, 0xFF6600, 0x666699, 0x969696,+        0x003366, 0x339966, 0x003300, 0x333300, 0x993300, 0x993366, 0x333399, 0x333333+    )+     private fun themeSlot(idx: Int): String = when (idx) {         0 -> "lt1"; 1 -> "dk1"; 2 -> "lt2"; 3 -> "dk2"         4 -> "accent1"; 5 -> "accent2"; 6 -> "accent3"; 7 -> "accent4"; 8 -> "accent5"; 9 -> "accent6"@@ -323,7 +352,7 @@ internal object OoxmlXlsx {         val hyperlinkRefs = mutableListOf<Triple<String, String?, String?>>() // ref, rId, location         val condFormats = mutableListOf<Pair<String, List<CfRule>>>() // sqref -> rules         val valRefs = mutableListOf<Pair<String, List<String>>>()-        val sharedFormulas = HashMap<Int, String>()+        val sharedFormulas = HashMap<Int, SharedFormulaDef>()         var curCells: MutableList<Pair<Int, OdfCell>>? = null         var curRowHidden = false         var rowIndex = 0@@ -363,7 +392,7 @@ internal object OoxmlXlsx {                     "c" -> if (curCells != null) {                         val ref = OoxmlXml.attr(parser, "r") ?: ""                         val ci = if (ref.isNotEmpty()) OoxmlXml.colIndex(ref) else curCells.size-                        curCells.add(ci to parseCell(parser, shared, styles, sharedFormulas))+                        curCells.add(ci to parseCell(parser, shared, styles, sharedFormulas, rowIndex, ci))                     }                     "mergeCell" -> OoxmlXml.attr(parser, "ref")?.let { merges.add(it) }                     "dataValidation" -> parseDataValidation(parser)?.let { (v, refs) ->@@ -443,7 +472,13 @@ internal object OoxmlXlsx {         return (0..maxCol).map { map[it] }     } -    private fun parseCell(parser: XmlPullParser, shared: List<String>, styles: StyleTable, sharedFormulas: MutableMap<Int, String>): OdfCell {+    /** Master definition of a shared formula: the master's A1 body and its 0-based row/col. */+    private class SharedFormulaDef(val a1: String, val row: Int, val col: Int)++    private fun parseCell(+        parser: XmlPullParser, shared: List<String>, styles: StyleTable,+        sharedFormulas: MutableMap<Int, SharedFormulaDef>, cellRow: Int, cellCol: Int+    ): OdfCell {         val type = OoxmlXml.attr(parser, "t")         val styleIdx = OoxmlXml.attr(parser, "s")?.toIntOrNull()         val depth = parser.depth@@ -460,8 +495,15 @@ internal object OoxmlXlsx {                     val si = OoxmlXml.attr(parser, "si")?.toIntOrNull()                     val f = OoxmlXml.readElementText(parser, "f")                     formula = when {-                        ft == "shared" && f.isNotBlank() -> ExcelFormula.toOdf(f).also { if (si != null) sharedFormulas[si] = it }-                        ft == "shared" && f.isBlank() -> si?.let { sharedFormulas[it] }+                        // Master of a shared formula: remember its A1 body + position for dependents.+                        ft == "shared" && f.isNotBlank() -> {+                            if (si != null) sharedFormulas[si] = SharedFormulaDef(f, cellRow, cellCol)+                            ExcelFormula.toOdf(f)+                        }+                        // Dependent: re-base the master's relative refs to this cell before translating.+                        ft == "shared" && f.isBlank() -> si?.let { sharedFormulas[it] }?.let { def ->+                            ExcelFormula.toOdf(ExcelFormula.shift(def.a1, cellRow - def.row, cellCol - def.col))+                        }                         f.isNotBlank() -> ExcelFormula.toOdf(f)                         else -> null                     }@@ -487,7 +529,14 @@ internal object OoxmlXlsx {                 else OdfCell(text = value ?: "")             }         }+        val resolvedFmt = xf?.let { if (it.applyNumberFormat || it.numFmtId != 0) styles.numberFormat(it.numFmtId) else null } ?: base.numberFormat+        // Excel stores the raw number (e.g. a date serial "45292"); the display string must be+        // formatted per the number format so dates/percent/currency don't show as bare numbers.+        val fmtForDisplay = resolvedFmt ?: if (base.valueType == "date") OdfNumberFormat(isDate = true) else null+        val displayText = if (base.numberValue != null && base.valueType != "boolean" && fmtForDisplay != null)+            OdfFormulaEngine.formatWithStyle(base.numberValue!!, fmtForDisplay) else base.text         return base.copy(+            text = displayText,             formula = formula ?: base.formula,             backgroundColor = cellStyle.fill,             textColor = cellStyle.fontColor,@@ -496,7 +545,7 @@ internal object OoxmlXlsx {             alignment = cellStyle.align,             borders = cellStyle.borders?.takeIf { !it.isEmpty() },             borderColor = cellStyle.borders?.let { OdfBorders.renderColor(it.top ?: it.left) },-            numberFormat = xf?.let { if (it.applyNumberFormat || it.numFmtId != 0) styles.numberFormat(it.numFmtId) else null } ?: base.numberFormat,+            numberFormat = resolvedFmt,             wrap = cellStyle.wrap,             textRotation = cellStyle.rotation,             verticalAlign = cellStyle.valign
office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.ktindex 2f3729f4b5..348b66b46e 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt@@ -79,10 +79,12 @@ import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.ColorMatrix import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.layout.layout import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.rotate-import androidx.compose.ui.draw.rotate import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester@@ -868,8 +870,18 @@ private fun TableView(     Column(Modifier.fillMaxWidth().padding(vertical = 8.dp).horizontalScroll(rememberScrollState())) {         for ((r, row) in table.rows.withIndex()) {             Row(Modifier.height(IntrinsicSize.Min)) {+                var colspanSkip = 0                 for ((c, cell) in row.cells.withIndex()) {-                    if (cell.isCovered) continue+                    if (cell.isCovered) {+                        // Covered by a horizontal merge to its left: the anchor already claimed the width.+                        if (colspanSkip > 0) { colspanSkip--; continue }+                        // Covered by a vertical (row) merge from above: render an aligned placeholder so+                        // columns below the merge don't collapse and shift left.+                        Box(Modifier.width(colWidthDp(c, 1)).fillMaxHeight()+                            .border(0.7.dp, MaterialTheme.colorScheme.outline)) {}+                        continue+                    }+                    colspanSkip = if (cell.colSpan > 1) cell.colSpan - 1 else 0                     Box(                         Modifier.width(colWidthDp(c, cell.colSpan))                             .fillMaxHeight()@@ -910,13 +922,46 @@ private fun EditableCell(cell: OdfTableCell, onSurface: Color, mult: Float, onFo     ) } +/** Rotation that swaps the layout footprint for 90°/270° turns so the image isn't squeezed/clipped. */+private fun Modifier.rotateForDisplay(degrees: Float): Modifier {+    if (degrees == 0f) return this+    val norm = ((degrees % 360f) + 360f) % 360f+    val quarterTurn = norm in 45f..135f || norm in 225f..315f+    return if (!quarterTurn) this.rotate(degrees)+    else this+        .layout { measurable, constraints ->+            val placeable = measurable.measure(constraints)+            layout(placeable.height, placeable.width) {+                placeable.place((placeable.height - placeable.width) / 2, (placeable.width - placeable.height) / 2)+            }+        }+        .rotate(degrees)+}++/** Draw alpha (0..1) from draw:image-opacity. */+private fun OdfImage.alphaValue(): Float = (opacityPercent / 100f).coerceIn(0f, 1f)++/** ColorFilter for draw:color-mode (greyscale/mono/watermark), or null for "standard". */+private fun OdfImage.effectFilter(): ColorFilter? = when (colorMode) {+    "greyscale", "mono" -> ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) })+    "watermark" -> ColorFilter.colorMatrix(ColorMatrix(floatArrayOf(+        0.4f, 0f, 0f, 0f, 140f,+        0f, 0.4f, 0f, 0f, 140f,+        0f, 0f, 0.4f, 0f, 140f,+        0f, 0f, 0f, 1f, 0f+    )))+    else -> null+}+ @Composable fun OdfImageView(image: OdfImage, modifier: Modifier = Modifier) {     val bitmap = remember(image.path, image.imageData.size) {         if (image.imageData.isNotEmpty()) try { BitmapFactory.decodeByteArray(image.imageData, 0, image.imageData.size) } catch (_: Exception) { null } else null     }     if (bitmap != null) {-        val rot = if (image.rotationDegrees != 0f) Modifier.rotate(image.rotationDegrees) else Modifier+        val rot = Modifier.rotateForDisplay(image.rotationDegrees)+        val imgAlpha = image.alphaValue()+        val imgFilter = image.effectFilter()         val hasCrop = image.cropLeftPct > 0f || image.cropTopPct > 0f || image.cropRightPct > 0f || image.cropBottomPct > 0f         if (hasCrop) {             // Non-destructive crop: draw only the visible source rectangle, scaled to fill. (Phase 5)@@ -938,7 +983,9 @@ fun OdfImageView(image: OdfImage, modifier: Modifier = Modifier) {                     srcOffset = IntOffset(srcX, srcY),                     srcSize = IntSize(srcW, srcH),                     dstOffset = IntOffset.Zero,-                    dstSize = IntSize(size.width.toInt().coerceAtLeast(1), size.height.toInt().coerceAtLeast(1))+                    dstSize = IntSize(size.width.toInt().coerceAtLeast(1), size.height.toInt().coerceAtLeast(1)),+                    alpha = imgAlpha,+                    colorFilter = imgFilter                 )             }             return@@ -951,14 +998,14 @@ fun OdfImageView(image: OdfImage, modifier: Modifier = Modifier) {             Image(                 bitmap = bitmap.asImageBitmap(), contentDescription = null,                 modifier = modifier.width(widthDp.dp).aspectRatio(aspect).then(rot).padding(vertical = 4.dp),-                contentScale = ContentScale.Fit+                contentScale = ContentScale.Fit, alpha = imgAlpha, colorFilter = imgFilter             )         } else {             val aspect = if (bitmap.height > 0) bitmap.width.toFloat() / bitmap.height.toFloat() else 1.5f             Image(                 bitmap = bitmap.asImageBitmap(), contentDescription = null,                 modifier = modifier.fillMaxWidth().aspectRatio(aspect.coerceIn(0.3f, 4f)).then(rot).padding(vertical = 4.dp),-                contentScale = ContentScale.Fit+                contentScale = ContentScale.Fit, alpha = imgAlpha, colorFilter = imgFilter             )         }     } else {@@ -979,6 +1026,7 @@ private fun formatAxis(v: Float): String = if (v == v.toLong().toFloat()) v.toLo private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {     val onSurface = MaterialTheme.colorScheme.onSurface     val gridColor = MaterialTheme.colorScheme.outlineVariant+    val surfaceColor = MaterialTheme.colorScheme.surface     Column(Modifier.fillMaxWidth().clickable { onClick() }.padding(vertical = 12.dp)) {         chart.title?.let { Text(it, style = MaterialTheme.typography.titleSmall, color = onSurface, modifier = Modifier.padding(bottom = 4.dp)) }         // Legend@@ -994,21 +1042,28 @@ private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {         Spacer(Modifier.height(8.dp))         val labelArgb = onSurface.toArgb()         Canvas(Modifier.fillMaxWidth().height(240.dp)) {-            val maxV = (chart.series.flatMap { it.values }.maxOrNull() ?: 1f).coerceAtLeast(1f)+            val allVals = chart.series.flatMap { it.values }+            // Include 0 in the range so negative values plot below the baseline instead of vanishing.+            val maxV = maxOf(allVals.maxOrNull() ?: 1f, 0f).let { if (it <= 0f) 1f else it }+            val minV = minOf(allVals.minOrNull() ?: 0f, 0f)+            val range = (maxV - minV).coerceAtLeast(1f)             val leftPad = 72f; val bottomPad = 56f; val topPad = 12f; val rightPad = 12f             val plotW = size.width - leftPad - rightPad             val plotH = size.height - bottomPad - topPad+            val yFor = { v: Float -> topPad + plotH - plotH * ((v - minV) / range) }+            val baselineY = yFor(0f)             val axisPaint = android.graphics.Paint().apply { color = labelArgb; textSize = 26f; isAntiAlias = true }             val centerPaint = android.graphics.Paint().apply { color = labelArgb; textSize = 26f; isAntiAlias = true; textAlign = android.graphics.Paint.Align.CENTER }             val steps = 5             for (s in 0..steps) {-                val v = maxV * s / steps-                val y = topPad + plotH - plotH * s / steps+                val v = minV + range * s / steps+                val y = yFor(v)                 drawLine(gridColor, Offset(leftPad, y), Offset(leftPad + plotW, y), 1f)                 drawContext.canvas.nativeCanvas.drawText(formatAxis(v), 6f, y + 9f, axisPaint)             }             drawLine(onSurface, Offset(leftPad, topPad), Offset(leftPad, topPad + plotH), 2f)-            drawLine(onSurface, Offset(leftPad, topPad + plotH), Offset(leftPad + plotW, topPad + plotH), 2f)+            // Baseline (value 0): bottom edge for all-positive data, mid-plot when negatives exist.+            drawLine(onSurface, Offset(leftPad, baselineY), Offset(leftPad + plotW, baselineY), 2f)             val catCount = chart.categories.size.coerceAtLeast(1)             when (chart.type) {                 ChartType.LINE -> {@@ -1018,7 +1073,7 @@ private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {                         var prev: Offset? = null                         for (ci in 0 until catCount) {                             val v = ser.values.getOrNull(ci) ?: 0f-                            val p = Offset(leftPad + stepX * ci, topPad + plotH - plotH * (v / maxV))+                            val p = Offset(leftPad + stepX * ci, yFor(v))                             prev?.let { drawLine(col, it, p, 4f) }                             drawCircle(col, 5f, p)                             prev = p@@ -1026,7 +1081,7 @@ private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {                     }                     for (ci in 0 until catCount) {                         val x = leftPad + (if (catCount > 1) plotW / (catCount - 1) else plotW) * ci-                        drawContext.canvas.nativeCanvas.drawText(chart.categories[ci], x, topPad + plotH + 34f, centerPaint)+                        drawContext.canvas.nativeCanvas.drawText(chart.categories.getOrElse(ci) { "" }, x, topPad + plotH + 34f, centerPaint)                     }                 }                 ChartType.SCATTER -> {@@ -1035,7 +1090,7 @@ private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {                         val col = chartPalette[si % chartPalette.size]                         for (ci in 0 until catCount) {                             val v = ser.values.getOrNull(ci) ?: 0f-                            drawCircle(col, 7f, Offset(leftPad + stepX * ci, topPad + plotH - plotH * (v / maxV)))+                            drawCircle(col, 7f, Offset(leftPad + stepX * ci, yFor(v)))                         }                     }                     for (ci in 0 until catCount) {@@ -1056,7 +1111,7 @@ private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {                     }                     if (chart.type == ChartType.DONUT) {                         val hole = d * 0.5f-                        drawArc(Color.White, 0f, 360f, true, Offset(topLeft.x + (d - hole) / 2, topLeft.y + (d - hole) / 2), Size(hole, hole))+                        drawArc(surfaceColor, 0f, 360f, true, Offset(topLeft.x + (d - hole) / 2, topLeft.y + (d - hole) / 2), Size(hole, hole))                     }                 }                 ChartType.STACKED_BAR -> {@@ -1084,8 +1139,10 @@ private fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {                         val gx = leftPad + groupW * ci + pad                         for (si in 0 until serCount) {                             val v = chart.series[si].values.getOrNull(ci) ?: 0f-                            val h = plotH * (v / maxV)-                            drawRect(chartPalette[si % chartPalette.size], Offset(gx + barW * si, topPad + plotH - h), Size(barW * 0.92f, h))+                            val yv = yFor(v)+                            val top = minOf(yv, baselineY)+                            val h = kotlin.math.abs(yv - baselineY)+                            drawRect(chartPalette[si % chartPalette.size], Offset(gx + barW * si, top), Size(barW * 0.92f, h))                         }                         drawContext.canvas.nativeCanvas.drawText(chart.categories.getOrElse(ci) { "" }, leftPad + groupW * ci + groupW / 2, topPad + plotH + 34f, centerPaint)                     }@@ -1848,6 +1905,7 @@ private fun SlideTextEditor(key: String, paragraphs: List<OdfParagraph>, fontSca @Composable private fun PositionedFrame(frame: OdfFrame, fontScale: Float, editing: Boolean = false, editKey: String = "", onTextChange: (String) -> Unit = {}) {     Box(Modifier.fillMaxSize()+        .then(if (frame.rotationDegrees != 0f) Modifier.rotate(frame.rotationDegrees) else Modifier)         .then(frame.fillColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)         .then(frame.strokeColor?.let { Modifier.border((frame.strokeWidth ?: 1f).dp.coerceAtLeast(0.5.dp), Color(it.toInt())) } ?: Modifier)     ) {@@ -1883,7 +1941,13 @@ private fun PositionedShape(shape: OdfShape, fontScale: Float, editing: Boolean             when (shape) {                 is OdfShape.Rect -> { if (fillBrush != null) drawRect(fillBrush) else drawRect(fillColor); drawRect(strokeColor, style = strokeStyle) }                 is OdfShape.Ellipse -> { if (fillBrush != null) drawOval(fillBrush) else drawOval(fillColor); drawOval(strokeColor, style = strokeStyle) }-                is OdfShape.Line -> drawLine(strokeColor, Offset.Zero, Offset(size.width, size.height), strokeW, pathEffect = dashEffect)+                is OdfShape.Line -> {+                    // Draw between the actual endpoints: pick the box corner matching endpoint 1 so+                    // negative-slope lines (bottom-left -> top-right) aren't mirrored.+                    val sx = if (shape.x <= shape.x2) 0f else size.width+                    val sy = if (shape.y <= shape.y2) 0f else size.height+                    drawLine(strokeColor, Offset(sx, sy), Offset(size.width - sx, size.height - sy), strokeW, pathEffect = dashEffect)+                }                 is OdfShape.CustomShape -> { if (fillBrush != null) drawRect(fillBrush) else drawRect(fillColor); drawRect(strokeColor, style = strokeStyle) }                 is OdfShape.Polyline -> {                     if (shape.points.size >= 2) {
office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.ktindex 5c57fbf28d..f9de0b92f2 100644--- a/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt+++ b/office/src/test/java/com/vayunmathur/office/util/OfficeSharingE2ETest.kt@@ -26,7 +26,7 @@ class OfficeSharingE2ETest {      private class MemStore : E2eeKeyStore {         private val m = HashMap<String, ByteArray>()-        override fun getBytes(name: String) = m[name]+        override suspend fun getBytes(name: String) = m[name]         override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {             if (onlyIfAbsent && m.containsKey(name)) return             m[name] = value