Modern Apps git

← Modern-Apps.git

office: various improvements

Commit
2037eb1530b35206c8a1892205e634d538746c0f
Author
Vayun Mathur <[email protected]>
When
2026-06-23 20:44 UTC (5 months ago)
Parents
c69e931

Diff

office/src/main/java/com/vayunmathur/office/MainActivity.kt
diff --git a/office/src/main/java/com/vayunmathur/office/MainActivity.kt b/office/src/main/java/com/vayunmathur/office/MainActivity.ktindex 576f80708d..e8c9ee9fbf 100644--- a/office/src/main/java/com/vayunmathur/office/MainActivity.kt+++ b/office/src/main/java/com/vayunmathur/office/MainActivity.kt@@ -75,6 +75,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight@@ -220,6 +221,7 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:     var activeSlideEl by remember { mutableIntStateOf(-1) }     var showCellTextColor by remember { mutableStateOf(false) }     var showCellBgColor by remember { mutableStateOf(false) }+    var showCellBorderColor by remember { mutableStateOf(false) }     var showSlideTextColor by remember { mutableStateOf(false) }     var showSlideFillColor by remember { mutableStateOf(false) }     var showSlideStrokeColor by remember { mutableStateOf(false) }@@ -235,6 +237,20 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:     val canUndo by viewModel.canUndo.collectAsState()     val canRedo by viewModel.canRedo.collectAsState()     val autoSaveEnabled by viewModel.autoSaveEnabled.collectAsState()+    val nightMode by viewModel.nightMode.collectAsState()+    var showWordBar by remember { mutableStateOf(false) }+    var findMatches by remember { mutableStateOf<List<Int>>(emptyList()) }+    var findIndex by remember { mutableIntStateOf(0) }+    val selectionInvalidation by viewModel.selectionInvalidation.collectAsState()++    // A4: reset hoisted selection whenever the document changes shape (undo/redo) so+    // formatting/color/delete never target a stale cell/element.+    LaunchedEffect(selectionInvalidation) {+        activeCell = null+        activeSlideEl = -1+        activeRunStart = -1; activeRunEnd = -1+        activeTableBlock = -1; activeTableRow = -1; activeTableCol = -1+    }      val isTextDoc = document is OdfDocument.TextDocument     val isSpreadsheet = document is OdfDocument.Spreadsheet@@ -354,6 +370,7 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                                     DropdownMenuItem(text = { Text("Save") }, enabled = hasUnsavedChanges, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.save_24px), null) }, onClick = { fileMenu = false; viewModel.save() })                                     DropdownMenuItem(text = { Text("Save As…") }, onClick = { fileMenu = false; saveAsLauncher.launch(document.title) })                                     DropdownMenuItem(text = { Text(stringResource(R.string.print_doc)) }, onClick = { fileMenu = false; printDocument(activity, document) })+                                    DropdownMenuItem(text = { Text("Export to PDF…") }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.outline_file_download_24), null) }, onClick = { fileMenu = false; printDocument(activity, document) })                                     viewModel.documentUri?.let { uri ->                                         DropdownMenuItem(text = { Text(stringResource(R.string.share)) }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.share_24px), null) }, onClick = { fileMenu = false; context.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { type = "*/*"; putExtra(Intent.EXTRA_STREAM, uri); addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) }, null)) })                                     }@@ -393,6 +410,8 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                                 DropdownMenu(expanded = viewMenu, onDismissRequest = { viewMenu = false }) {                                     if (isTextDoc && (headings.isNotEmpty() || bookmarks.isNotEmpty())) DropdownMenuItem(text = { Text(stringResource(R.string.outline)) }, onClick = { viewMenu = false; scope.launch { drawerState.open() } })                                     DropdownMenuItem(text = { Text("Zoom text") }, onClick = { viewMenu = false; showFontControl = !showFontControl })+                                    DropdownMenuItem(text = { Text(if (nightMode) "✓ Night reading mode" else "Night reading mode") }, onClick = { viewMenu = false; viewModel.toggleNightMode() })+                                    if (isTextDoc) DropdownMenuItem(text = { Text(if (showWordBar) "✓ Word count bar" else "Word count bar") }, onClick = { viewMenu = false; showWordBar = !showWordBar })                                     if (isTextDoc && wordCount > 0) DropdownMenuItem(text = { Text("$wordCount words · $charCount chars · ~${readingTime} min") }, enabled = false, onClick = { })                                     if (isPresentation) DropdownMenuItem(text = { Text("Presentation timer") }, onClick = { viewMenu = false; showTimer = !showTimer })                                 }@@ -420,6 +439,21 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                                         IconButton(onClick = { showSearch = false; searchQuery = ""; showReplaceBar = false }) { Icon(painterResource(com.vayunmathur.library.R.drawable.close_24px), contentDescription = "Close search") }                                     }                                 })+                            if (isTextDoc && searchQuery.isNotEmpty()) {+                                Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {+                                    fun jump(delta: Int) {+                                        val matches = viewModel.findMatchBlocks(searchQuery, matchCase, wholeWord)+                                        findMatches = matches+                                        if (matches.isEmpty()) return+                                        findIndex = ((findIndex + delta) % matches.size + matches.size) % matches.size+                                        scope.launch { listState.animateScrollToItem(matches[findIndex].coerceIn(0, (document as OdfDocument.TextDocument).content.size - 1)) }+                                    }+                                    val total = remember(searchQuery, matchCase, wholeWord, document) { viewModel.findMatchBlocks(searchQuery, matchCase, wholeWord).size }+                                    TextButton(onClick = { jump(-1) }) { Text("◀ Prev") }+                                    TextButton(onClick = { jump(1) }) { Text("Next ▶") }+                                    Text(if (total > 0) "${(findIndex % total) + 1}/$total" else "0/0", style = MaterialTheme.typography.labelMedium)+                                }+                            }                             AnimatedVisibility(visible = showReplaceBar && searchQuery.isNotEmpty()) {                                 Column {                                     Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {@@ -445,6 +479,13 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                             TextButton(onClick = { fontSizeMultiplier = 1f }) { Text(stringResource(R.string.reset)) }                         }                     }+                    AnimatedVisibility(visible = showWordBar && isTextDoc) {+                        Surface(color = MaterialTheme.colorScheme.surfaceVariant) {+                            Text("$wordCount words · $charCount characters · ~$readingTime min read",+                                style = MaterialTheme.typography.labelMedium,+                                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp))+                        }+                    }                 }             },             bottomBar = {@@ -479,7 +520,8 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                         },                         onInsertChart = { editingChartBlock = -1; chartForSlide = isPresentation; chartForSheet = isSpreadsheet; showChartEditor = true },                         onInsertTable = { showInsertTable = true },-                        onDeleteElement = { if (activeSlideEl >= 0) { viewModel.deleteSlideElement(activeSlide, activeSlideEl); activeSlideEl = -1 } }+                        onDeleteElement = { if (activeSlideEl >= 0) { viewModel.deleteSlideElement(activeSlide, activeSlideEl); activeSlideEl = -1 } },+                        onCellBorder = { showCellBorderColor = true }                     )                     OfficeBottomBar(document, formatTarget, caps, viewModel, actions, activeTableBlock, activeTableRow, activeTableCol)                 }@@ -520,6 +562,8 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                         onCropImage = { s, e -> cropSlideTarget = s to e })                     is OdfDocument.Drawing -> DrawingView(document)                 }+                // Night reading mode: a view-only dimming scrim (does not modify or save the document). (C4)+                if (nightMode) Box(Modifier.matchParentSize().background(Color(0x660E1116)))             }         }     }@@ -558,6 +602,10 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:         val (s, r, c) = activeCell!!         ColorPickerDialog("Background Color", onColorSelected = { viewModel.setCellBgColor(s, r, c, it) }, onDismiss = { showCellBgColor = false })     }+    if (showCellBorderColor && (activeCell?.second ?: -1) >= 0) {+        val (s, r, c) = activeCell!!+        ColorPickerDialog("Border Color", onColorSelected = { viewModel.setCellBorder(s, r, c, it) }, onDismiss = { showCellBorderColor = false })+    }     if (showSlideTextColor && activeSlideEl >= 0) {         ColorPickerDialog("Text Color", onColorSelected = { viewModel.setSlideElementColor(activeSlide, activeSlideEl, it) }, onDismiss = { showSlideTextColor = false })     }
office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.ktindex 2531423ca0..4f8aa4a0e5 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt@@ -85,7 +85,9 @@ data class OdfParagraph(     val listNumberPrefix: String = "",     val listNumberSuffix: String = ".",     // Tab stop positions in px (96dpi). (A4)-    val tabStops: List<Float> = emptyList()+    val tabStops: List<Float> = emptyList(),+    // Emit fo:break-before="page" on this paragraph's style. (B4)+    val breakBeforePage: Boolean = false )  enum class ParagraphStyle { HEADING1, HEADING2, HEADING3, HEADING4, BODY, LIST_ITEM, TABLE_HEADER }@@ -152,6 +154,10 @@ data class OdfImage(     val anchorType: String = "",     // Rotation in degrees clockwise (E38).     val rotationDegrees: Float = 0f,+    // Natural (intrinsic) pixel size of the source image, used to convert crop+    // fractions to absolute ODF fo:clip lengths. 0 = unknown. (A7)+    val naturalWidthPx: Float = 0f,+    val naturalHeightPx: Float = 0f,     // Non-destructive crop insets as fractions of the source image [0,1). (Phase 5)     val cropLeftPct: Float = 0f,     val cropTopPct: Float = 0f,
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 03a3d0bdbc..a58ad114c7 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt@@ -1,9 +1,16 @@ package com.vayunmathur.office.odf  import kotlin.math.abs+import kotlin.math.ceil+import kotlin.math.exp+import kotlin.math.floor+import kotlin.math.ln+import kotlin.math.log10 import kotlin.math.pow import kotlin.math.roundToLong+import kotlin.math.sign import kotlin.math.sqrt+import kotlin.math.truncate  /**  * Minimal OpenFormula evaluator for spreadsheet cells (H49).@@ -258,6 +265,49 @@ object OdfFormulaEngine {                     "AND" -> if (nums.isNotEmpty() && nums.all { it != 0.0 }) 1.0 else 0.0                     "OR" -> if (nums.any { it != 0.0 }) 1.0 else 0.0                     "NOT" -> if ((flat.firstOrNull() ?: 0.0) == 0.0) 1.0 else 0.0+                    "PRODUCT" -> if (nums.isEmpty()) 0.0 else nums.fold(1.0) { a, b -> a * b }+                    "MEDIAN" -> if (nums.isEmpty()) Double.NaN else {+                        val s = nums.sorted(); val n = s.size+                        if (n % 2 == 1) s[n / 2] else (s[n / 2 - 1] + s[n / 2]) / 2.0+                    }+                    "STDEV" -> if (nums.size < 2) Double.NaN else {+                        val m = nums.average(); sqrt(nums.sumOf { (it - m).pow(2) } / (nums.size - 1))+                    }+                    "VAR" -> if (nums.size < 2) Double.NaN else {+                        val m = nums.average(); nums.sumOf { (it - m).pow(2) } / (nums.size - 1)+                    }+                    "INT" -> floor(flat.firstOrNull() ?: 0.0)+                    "TRUNC" -> truncate(flat.firstOrNull() ?: 0.0)+                    "SIGN" -> sign(flat.firstOrNull() ?: 0.0)+                    "EXP" -> exp(flat.firstOrNull() ?: 0.0)+                    "LN" -> ln(flat.firstOrNull() ?: 0.0)+                    "LOG10" -> log10(flat.firstOrNull() ?: 0.0)+                    "LOG" -> {+                        val v = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val base = args.getOrNull(1)?.firstOrNull() ?: 10.0+                        ln(v) / ln(base)+                    }+                    "CEILING" -> {+                        val v = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val step = args.getOrNull(1)?.firstOrNull() ?: 1.0+                        if (step == 0.0) 0.0 else ceil(v / step) * step+                    }+                    "FLOOR" -> {+                        val v = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val step = args.getOrNull(1)?.firstOrNull() ?: 1.0+                        if (step == 0.0) 0.0 else floor(v / step) * step+                    }+                    "ROUNDUP" -> {+                        val v = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val d = (args.getOrNull(1)?.firstOrNull() ?: 0.0).toInt()+                        val factor = 10.0.pow(d); ceil(abs(v) * factor) / factor * sign(v).let { if (it == 0.0) 1.0 else it }+                    }+                    "ROUNDDOWN" -> {+                        val v = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val d = (args.getOrNull(1)?.firstOrNull() ?: 0.0).toInt()+                        val factor = 10.0.pow(d); floor(abs(v) * factor) / factor * sign(v).let { if (it == 0.0) 1.0 else it }+                    }+                    "COUNTBLANK" -> 0.0                     else -> Double.NaN                 }             }
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 cc0f808428..d4825fd281 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt@@ -54,9 +54,9 @@ object OdfParser {         val type = detectType(contentXml)         return when (type) {             DocType.TEXT -> parseTextDocument(contentXml, styleMap, listStyleMap, fileName, metadata, images, headerFooter, objectContents)-            DocType.SPREADSHEET -> parseSpreadsheet(contentXml, styleMap, numberStyleMap, fileName, metadata, images)-            DocType.PRESENTATION -> parsePresentation(contentXml, styleMap, fileName, metadata, images)-            DocType.DRAWING -> parseDrawing(contentXml, styleMap, fileName, metadata, images)+            DocType.SPREADSHEET -> parseSpreadsheet(contentXml, styleMap, numberStyleMap, fileName, metadata, images, objectContents)+            DocType.PRESENTATION -> parsePresentation(contentXml, styleMap, fileName, metadata, images, objectContents)+            DocType.DRAWING -> parseDrawing(contentXml, styleMap, fileName, metadata, images, objectContents)         }     } @@ -179,6 +179,31 @@ object OdfParser {         return floatArrayOf(left, top, right, bottom)     } +    /** Parses fo:clip="rect(top right bottom left)" absolute lengths into [left, top, right, bottom] fractions+     *  using the natural image size (px@96). Returns null if no crop. (A7) */+    private fun parseClipLengths(value: String?, wPx: Float, hPx: Float): FloatArray? {+        if (value == null || wPx <= 0f || hPx <= 0f) return null+        val inner = value.substringAfter("rect(", "").substringBefore(")")+        if (inner.isBlank()) return null+        val parts = inner.trim().split(Regex("[ ,]+"))+        if (parts.size < 4) return null+        // If any token is a percentage, fall back to percent parsing.+        if (parts.any { it.trim().endsWith("%") }) return parseClip(value)+        fun frac(token: String, basePx: Float): Float = (parseDimension(token.trim()) / basePx).coerceIn(0f, 0.95f)+        val top = frac(parts[0], hPx); val right = frac(parts[1], wPx); val bottom = frac(parts[2], hPx); val left = frac(parts[3], wPx)+        if (top == 0f && right == 0f && bottom == 0f && left == 0f) return null+        return floatArrayOf(left, top, right, bottom)+    }++    /** Decodes the intrinsic pixel size of an encoded image without allocating the full bitmap. (A7) */+    private fun decodeNaturalSize(bytes: ByteArray): Pair<Float, Float> {+        return try {+            val opts = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }+            android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)+            opts.outWidth.toFloat() to opts.outHeight.toFloat()+        } catch (_: Exception) { 0f to 0f }+    }+     /** Converts an ODF draw:transform rotate(theta) into degrees clockwise for Compose (E38). */     private fun parseRotationDegrees(transform: String?): Float {         if (transform == null) return 0f@@ -220,7 +245,8 @@ object OdfParser {         val paragraphBorderColor: Long? = null,         val tabStops: List<Float> = emptyList(),         val dataStyleName: String? = null,-        val cellWrap: Boolean = false+        val cellWrap: Boolean = false,+        val clip: String? = null     )      private fun parseStyles(xml: String): Map<String, StyleInfo> {@@ -258,6 +284,7 @@ object OdfParser {         var lineHeightPercent: Float? = null         var paraBorderColor: Long? = null         val tabStops = mutableListOf<Float>()+        var clipVal: String? = null          val depth = parser.depth         var eventType = parser.next()@@ -318,6 +345,7 @@ object OdfParser {                         }                         getAttr(parser, "stroke-color")?.let { drawStrokeColor = parseColor(it) }                         getAttr(parser, "stroke-width")?.let { drawStrokeWidth = parseDimension(it) }+                        getAttr(parser, "clip")?.let { clipVal = it }                     }                     "table-cell-properties" -> {                         getAttr(parser, "background-color")?.let { if (it != "transparent") cellBgColor = parseColor(it) }@@ -339,7 +367,7 @@ object OdfParser {             textAlign, marginLeft, marginTop, marginBottom, textIndent, paraBgColor,             breakBefore, breakAfter, drawFillColor, drawStrokeColor, drawStrokeWidth,             cellBgColor, cellBorderColor, writingMode, columnWidth,-            lineHeightPercent, paraBorderColor, tabStops, null, cellWrap+            lineHeightPercent, paraBorderColor, tabStops, null, cellWrap, clipVal         )     } @@ -379,7 +407,8 @@ object OdfParser {                 paragraphBorderColor = info.paragraphBorderColor ?: parent.paragraphBorderColor,                 tabStops = if (info.tabStops.isNotEmpty()) info.tabStops else parent.tabStops,                 dataStyleName = info.dataStyleName ?: parent.dataStyleName,-                cellWrap = info.cellWrap || parent.cellWrap+                cellWrap = info.cellWrap || parent.cellWrap,+                clip = info.clip ?: parent.clip             )         }         return info@@ -610,6 +639,7 @@ object OdfParser {         var pendingFrameW = 0f         var pendingFrameH = 0f         var pendingFrameClip: String? = null+        var pendingFrameStyleClip: String? = null          while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth && parser.name == endTag)) {             when (eventType) {@@ -635,14 +665,17 @@ object OdfParser {                         pendingFrameW = parseDimension(getAttr(parser, "width"))                         pendingFrameH = parseDimension(getAttr(parser, "height"))                         pendingFrameClip = getAttr(parser, "clip")+                        pendingFrameStyleClip = resolveStyle(getAttr(parser, "style-name"), styles).clip                     }                     "image" -> {                         val href = getAttr(parser, "href")                         val w = pendingFrameW                         val h = pendingFrameH-                        val clip = parseClip(pendingFrameClip)                         if (href != null && images.containsKey(href)) {-                            var img = OdfImage(path = href, imageData = images[href]!!, width = w, height = h)+                            val bytes = images[href]!!+                            val (nw, nh) = decodeNaturalSize(bytes)+                            val clip = parseClip(pendingFrameClip) ?: parseClipLengths(pendingFrameStyleClip, nw, nh)+                            var img = OdfImage(path = href, imageData = bytes, width = w, height = h, naturalWidthPx = nw, naturalHeightPx = nh)                             if (clip != null) img = img.copy(cropLeftPct = clip[0], cropTopPct = clip[1], cropRightPct = clip[2], cropBottomPct = clip[3])                             imagesOut?.add(img)                             skipElement(parser)@@ -656,7 +689,9 @@ object OdfParser {                                     if (imgEvent == XmlPullParser.TEXT) {                                         try {                                             val bytes = Base64.decode(parser.text.trim(), Base64.DEFAULT)-                                            var img = OdfImage(path = "inline", imageData = bytes, width = w, height = h)+                                            val (nw, nh) = decodeNaturalSize(bytes)+                                            val clip = parseClip(pendingFrameClip) ?: parseClipLengths(pendingFrameStyleClip, nw, nh)+                                            var img = OdfImage(path = "inline", imageData = bytes, width = w, height = h, naturalWidthPx = nw, naturalHeightPx = nh)                                             if (clip != null) img = img.copy(cropLeftPct = clip[0], cropTopPct = clip[1], cropRightPct = clip[2], cropBottomPct = clip[3])                                             imagesOut?.add(img)                                         } catch (_: Exception) {}@@ -1128,7 +1163,7 @@ object OdfParser {      private fun parseSpreadsheet(         xml: String, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>,-        title: String, metadata: OdfMetadata, images: Map<String, ByteArray>+        title: String, metadata: OdfMetadata, images: Map<String, ByteArray>, objectContents: Map<String, String> = emptyMap()     ): OdfDocument.Spreadsheet {         val sheets = mutableListOf<OdfSheet>()         val parser = newParser(xml)@@ -1137,7 +1172,7 @@ object OdfParser {         while (eventType != XmlPullParser.END_DOCUMENT) {             if (eventType == XmlPullParser.START_TAG && parser.name == "table" && parser.namespace?.contains("table") == true) {                 val name = getAttr(parser, "name") ?: "Sheet ${sheets.size + 1}"-                val result = parseSheetContent(parser, styles, numberStyles, images)+                val result = parseSheetContent(parser, styles, numberStyles, images, objectContents)                 sheets.add(OdfSheet(name, result.first, result.second, result.third))             }             eventType = parser.next()@@ -1145,7 +1180,7 @@ object OdfParser {         return OdfDocument.Spreadsheet(title, sheets, metadata, images)     } -    private fun parseSheetContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>, images: Map<String, ByteArray>): Triple<List<OdfRow>, List<Float?>, List<OdfSlideElement>> {+    private fun parseSheetContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>, images: Map<String, ByteArray>, objectContents: Map<String, String> = emptyMap()): Triple<List<OdfRow>, List<Float?>, List<OdfSlideElement>> {         val rows = mutableListOf<OdfRow>()         val columnWidths = mutableListOf<Float?>()         val floating = mutableListOf<OdfSlideElement>()@@ -1167,7 +1202,7 @@ object OdfParser {                         val cells = parseSpreadsheetCells(parser, styles, numberStyles)                         repeat(repeated.coerceAtMost(1000)) { rows.add(OdfRow(cells)) }                     }-                    "frame" -> if (isDraw) floating.add(OdfSlideElement.Frame(parseSingleFrame(parser, styles, images)))+                    "frame" -> if (isDraw) floating.add(OdfSlideElement.Frame(parseSingleFrame(parser, styles, images, objectContents)))                     "rect" -> if (isDraw) floating.add(OdfSlideElement.Shape(parseShape(parser, styles, "rect")))                     "ellipse" -> if (isDraw) floating.add(OdfSlideElement.Shape(parseShape(parser, styles, "ellipse")))                     "line" -> if (isDraw) floating.add(OdfSlideElement.Shape(parseShape(parser, styles, "line")))@@ -1238,17 +1273,19 @@ object OdfParser {      private fun parsePresentation(         xml: String, styles: Map<String, StyleInfo>,-        title: String, metadata: OdfMetadata, images: Map<String, ByteArray>+        title: String, metadata: OdfMetadata, images: Map<String, ByteArray>,+        objectContents: Map<String, String> = emptyMap()     ): OdfDocument.Presentation =-        OdfDocument.Presentation(title, parseSlides(xml, styles, images), metadata, images)+        OdfDocument.Presentation(title, parseSlides(xml, styles, images, objectContents), metadata, images)      private fun parseDrawing(         xml: String, styles: Map<String, StyleInfo>,-        title: String, metadata: OdfMetadata, images: Map<String, ByteArray>+        title: String, metadata: OdfMetadata, images: Map<String, ByteArray>,+        objectContents: Map<String, String> = emptyMap()     ): OdfDocument.Drawing =-        OdfDocument.Drawing(title, parseSlides(xml, styles, images), metadata, images)+        OdfDocument.Drawing(title, parseSlides(xml, styles, images, objectContents), metadata, images) -    private fun parseSlides(xml: String, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>): List<OdfSlide> {+    private fun parseSlides(xml: String, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>, objectContents: Map<String, String> = emptyMap()): List<OdfSlide> {         val slides = mutableListOf<OdfSlide>()         val parser = newParser(xml)         var eventType = parser.eventType@@ -1258,7 +1295,7 @@ object OdfParser {                 val name = getAttr(parser, "name") ?: "Slide ${slides.size + 1}"                 val drawStyleName = getAttr(parser, "style-name")                 val resolved = resolveStyle(drawStyleName, styles)-                val result = parseSlideContent(parser, styles, images)+                val result = parseSlideContent(parser, styles, images, objectContents)                 slides.add(OdfSlide(                     name = name, elements = result.elements,                     backgroundColor = resolved.drawFillColor, notes = result.notes@@ -1271,7 +1308,7 @@ object OdfParser {      private data class SlideParseResult(val elements: List<OdfSlideElement>, val notes: List<OdfParagraph>) -    private fun parseSlideContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>): SlideParseResult {+    private fun parseSlideContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>, objectContents: Map<String, String> = emptyMap()): SlideParseResult {         val elements = mutableListOf<OdfSlideElement>()         val notes = mutableListOf<OdfParagraph>()         val depth = parser.depth@@ -1279,7 +1316,7 @@ object OdfParser {          while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth)) {             if (eventType == XmlPullParser.START_TAG) when (parser.name) {-                "frame" -> elements.add(OdfSlideElement.Frame(parseSingleFrame(parser, styles, images)))+                "frame" -> elements.add(OdfSlideElement.Frame(parseSingleFrame(parser, styles, images, objectContents)))                 "rect" -> elements.add(OdfSlideElement.Shape(parseShape(parser, styles, "rect")))                 "ellipse" -> elements.add(OdfSlideElement.Shape(parseShape(parser, styles, "ellipse")))                 "line" -> elements.add(OdfSlideElement.Shape(parseShape(parser, styles, "line")))@@ -1289,7 +1326,7 @@ object OdfParser {                     var noteEvent = parser.next()                     while (!(noteEvent == XmlPullParser.END_TAG && parser.depth == noteDepth)) {                         if (noteEvent == XmlPullParser.START_TAG && parser.name == "frame") {-                            val frame = parseSingleFrame(parser, styles, images)+                            val frame = parseSingleFrame(parser, styles, images, objectContents)                             for (para in frame.paragraphs) {                                 if (para.spans.isNotEmpty()) notes.add(para)                             }@@ -1303,7 +1340,7 @@ object OdfParser {         return SlideParseResult(elements, notes)     } -    private fun parseSingleFrame(parser: XmlPullParser, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>): OdfFrame {+    private fun parseSingleFrame(parser: XmlPullParser, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>, objectContents: Map<String, String> = emptyMap()): OdfFrame {         val x = parseDimension(getAttr(parser, "x"))         val y = parseDimension(getAttr(parser, "y"))         val w = parseDimension(getAttr(parser, "width"))@@ -1315,6 +1352,7 @@ object OdfParser {          val paragraphs = mutableListOf<OdfParagraph>()         var image: OdfImage? = null+        var chart: OdfChart? = null         val depth = parser.depth         var eventType = parser.next() @@ -1333,10 +1371,18 @@ object OdfParser {                         boxEvent = parser.next()                     }                 }+                "object" -> {+                    // Embedded chart object referenced by ./Object N. (A8)+                    val href = getAttr(parser, "href")?.removePrefix("./")+                    val xml = href?.let { objectContents["$it/content.xml"] }+                    if (xml != null) parseChart(xml)?.let { chart = it }+                }                 "image" -> {                     val href = getAttr(parser, "href")                     if (href != null && images.containsKey(href)) {-                        image = OdfImage(path = href, imageData = images[href]!!, width = w, height = h, rotationDegrees = rot)+                        val bytes = images[href]!!+                        val (nw, nh) = decodeNaturalSize(bytes)+                        image = OdfImage(path = href, imageData = bytes, width = w, height = h, rotationDegrees = rot, naturalWidthPx = nw, naturalHeightPx = nh)                     }                     val imgDepth = parser.depth                     var imgEvent = parser.next()@@ -1346,7 +1392,8 @@ object OdfParser {                             if (imgEvent == XmlPullParser.TEXT) {                                 try {                                     val bytes = Base64.decode(parser.text.trim(), Base64.DEFAULT)-                                    image = OdfImage(path = "inline", imageData = bytes, width = w, height = h, rotationDegrees = rot)+                                    val (nw, nh) = decodeNaturalSize(bytes)+                                    image = OdfImage(path = "inline", imageData = bytes, width = w, height = h, rotationDegrees = rot, naturalWidthPx = nw, naturalHeightPx = nh)                                 } catch (_: Exception) { }                             }                         }@@ -1360,10 +1407,12 @@ object OdfParser {             }             eventType = parser.next()         }-        if (clip != null && image != null) {-            image = image.copy(cropLeftPct = clip[0], cropTopPct = clip[1], cropRightPct = clip[2], cropBottomPct = clip[3])+        if (image != null) {+            // Prefer the legacy inline percent clip; otherwise resolve absolute lengths from the graphic style. (A7)+            val frac = clip ?: parseClipLengths(resolved.clip, image.naturalWidthPx, image.naturalHeightPx)+            if (frac != null) image = image.copy(cropLeftPct = frac[0], cropTopPct = frac[1], cropRightPct = frac[2], cropBottomPct = frac[3])         }-        return OdfFrame(x, y, w, h, paragraphs, image, fillColor = resolved.drawFillColor, strokeColor = resolved.drawStrokeColor, strokeWidth = resolved.drawStrokeWidth)+        return OdfFrame(x, y, w, h, paragraphs, image, chart = chart, fillColor = resolved.drawFillColor, strokeColor = resolved.drawStrokeColor, strokeWidth = resolved.drawStrokeWidth)     }      private fun parseListInFrame(parser: XmlPullParser, styles: Map<String, StyleInfo>, images: Map<String, ByteArray>, paragraphs: MutableList<OdfParagraph>) {
office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.ktindex 493d547c35..8de372441b 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt@@ -1,16 +1,46 @@ package com.vayunmathur.office.odf  import androidx.compose.ui.text.style.TextAlign+import java.util.Locale  object OdfSerializer { -    fun serialize(document: OdfDocument): String {+    /** Extra package parts generated during serialization (inline images promoted to the package,+     *  embedded chart objects, and the manifest media types for those objects). (A6/A8) */+    data class SerResult(+        val contentXml: String,+        val images: Map<String, ByteArray>,+        val objects: Map<String, String>,+        val manifest: Map<String, String>+    )++    private class SerCtx(val flat: Boolean) {+        val images = LinkedHashMap<String, ByteArray>()+        val objects = LinkedHashMap<String, String>()+        val manifest = LinkedHashMap<String, String>()+        private var imgN = 0+        private var objN = 0+        fun nextImagePath(ext: String): String { imgN++; return "Pictures/inline$imgN.$ext" }+        fun nextObjectDir(): String { objN++; return "Object Chart $objN" }+    }++    /** Content-only serialization (used for in-package content.xml via [serializePackaged] and flat export). */+    fun serialize(document: OdfDocument): String = serializeInner(document, SerCtx(flat = true))++    /** Full package serialization: content.xml plus generated inline images and embedded chart objects. */+    fun serializePackaged(document: OdfDocument): SerResult {+        val ctx = SerCtx(flat = false)+        val xml = serializeInner(document, ctx)+        return SerResult(xml, ctx.images, ctx.objects, ctx.manifest)+    }++    private fun serializeInner(document: OdfDocument, ctx: SerCtx): String {         return when (document) {-            is OdfDocument.TextDocument -> serializeTextDocument(document)-            is OdfDocument.Spreadsheet -> serializeSpreadsheet(document)-            is OdfDocument.Presentation -> serializePresentation(document)+            is OdfDocument.TextDocument -> serializeTextDocument(document, ctx)+            is OdfDocument.Spreadsheet -> serializeSpreadsheet(document, ctx)+            is OdfDocument.Presentation -> serializePresentation(document, ctx)             is OdfDocument.Drawing -> serializePresentation(-                OdfDocument.Presentation(document.title, document.pages, document.metadata, document.images)+                OdfDocument.Presentation(document.title, document.pages, document.metadata, document.images), ctx             )         }     }@@ -51,20 +81,26 @@ object OdfSerializer {         return sb.toString()     } -    private fun serializeTextDocument(doc: OdfDocument.TextDocument): String {+    private fun serializeTextDocument(doc: OdfDocument.TextDocument, ctx: SerCtx): String {         val styles = mutableMapOf<String, SpanStyleDef>()         val paraStyles = mutableMapOf<String, ParaStyleDef>()+        val graphicStyles = LinkedHashMap<String, GraphicStyleDef>()         val body = StringBuilder() +        // Bookmarks keyed by the content-block index they precede. (B3)+        val bookmarksByIndex = HashMap<Int, MutableList<String>>()+        for (bk in doc.bookmarks) bookmarksByIndex.getOrPut(bk.contentIndex) { mutableListOf() }.add(bk.name)+         var listOpen = false-        for (block in doc.content) {+        doc.content.forEachIndexed { index, block ->+            val leadingBookmarks = bookmarksByIndex[index] ?: emptyList()             when (block) {                 is OdfContentBlock.Paragraph -> {                     val para = block.paragraph                     if (para.style == ParagraphStyle.LIST_ITEM) {                         if (!listOpen) { body.append("<text:list>"); listOpen = true }                         body.append("<text:list-item>")-                        serializeParagraph(body, para, styles, paraStyles, "text:p")+                        serializeParagraph(body, para, styles, paraStyles, "text:p", leadingBookmarks)                         body.append("</text:list-item>")                     } else {                         if (listOpen) { body.append("</text:list>"); listOpen = false }@@ -73,7 +109,7 @@ object OdfSerializer {                             ParagraphStyle.HEADING3, ParagraphStyle.HEADING4 -> "text:h"                             else -> "text:p"                         }-                        serializeParagraph(body, para, styles, paraStyles, tag)+                        serializeParagraph(body, para, styles, paraStyles, tag, leadingBookmarks)                     }                 }                 is OdfContentBlock.Table -> {@@ -82,11 +118,11 @@ object OdfSerializer {                 }                 is OdfContentBlock.Image -> {                     if (listOpen) { body.append("</text:list>"); listOpen = false }-                    serializeImageRef(body, block.image)+                    serializeImageRef(body, block.image, graphicStyles, ctx)                 }                 is OdfContentBlock.Chart -> {                     if (listOpen) { body.append("</text:list>"); listOpen = false }-                    // Charts are embedded OLE objects; not re-serialized (preserved only when not re-saved).+                    serializeChartFrame(body, block.chart, 0f, 0f, 480f, 320f, "paragraph", styles, paraStyles, ctx)                 }                 is OdfContentBlock.Formula -> {                     if (listOpen) { body.append("</text:list>"); listOpen = false }@@ -94,15 +130,18 @@ object OdfSerializer {                 }                 is OdfContentBlock.PageBreak -> {                     if (listOpen) { body.append("</text:list>"); listOpen = false }+                    // Emit an empty paragraph carrying a page-break-before style. (B4)+                    val name = getOrCreateParaStyle(OdfParagraph(emptyList(), breakBeforePage = true), paraStyles)+                    body.append("""<text:p text:style-name="$name"/>""")                 }             }         }         if (listOpen) body.append("</text:list>") -        return buildDocument("office:text", styles, paraStyles, LinkedHashMap(), LinkedHashMap(), LinkedHashMap(), body.toString())+        return buildDocument("office:text", styles, paraStyles, LinkedHashMap(), LinkedHashMap(), graphicStyles, body.toString())     } -    private fun serializeSpreadsheet(doc: OdfDocument.Spreadsheet): String {+    private fun serializeSpreadsheet(doc: OdfDocument.Spreadsheet, ctx: SerCtx): String {         val cellStyles = LinkedHashMap<String, CellStyleDef>()         val colStyles = LinkedHashMap<String, Float>()         val spanStyles = mutableMapOf<String, SpanStyleDef>()@@ -149,7 +188,7 @@ object OdfSerializer {             // Floating objects anchored to the sheet (Phase 4).             for (element in sheet.floating) {                 when (element) {-                    is OdfSlideElement.Frame -> serializeFrame(body, element.frame, spanStyles, paraStyles, graphicStyles)+                    is OdfSlideElement.Frame -> serializeFrame(body, element.frame, spanStyles, paraStyles, graphicStyles, ctx)                     is OdfSlideElement.Shape -> serializeShape(body, element.shape, spanStyles, paraStyles, graphicStyles)                 }             }@@ -158,29 +197,40 @@ object OdfSerializer {         return buildDocument("office:spreadsheet", spanStyles, paraStyles, cellStyles, colStyles, graphicStyles, body.toString())     } -    private fun serializePresentation(doc: OdfDocument.Presentation): String {+    private fun serializePresentation(doc: OdfDocument.Presentation, ctx: SerCtx): String {         val styles = mutableMapOf<String, SpanStyleDef>()         val paraStyles = mutableMapOf<String, ParaStyleDef>()         val graphicStyles = LinkedHashMap<String, GraphicStyleDef>()+        val drawPageStyles = LinkedHashMap<String, Long>()         val body = StringBuilder()         for (slide in doc.slides) {-            body.append("""<draw:page draw:name="${esc(slide.name)}">""")+            body.append("<draw:page")+            // Slide background fill via a drawing-page style. (B2)+            slide.backgroundColor?.let { body.append(""" draw:style-name="${getOrCreateDrawPageStyle(it, drawPageStyles)}"""") }+            body.append(""" draw:name="${esc(slide.name)}">""")             for (element in slide.elements) {                 when (element) {-                    is OdfSlideElement.Frame -> serializeFrame(body, element.frame, styles, paraStyles, graphicStyles)+                    is OdfSlideElement.Frame -> serializeFrame(body, element.frame, styles, paraStyles, graphicStyles, ctx)                     is OdfSlideElement.Shape -> serializeShape(body, element.shape, styles, paraStyles, graphicStyles)                 }             }+            // Speaker notes. (B2)+            if (slide.notes.isNotEmpty()) {+                body.append("<presentation:notes><draw:frame svg:x=\"1.5cm\" svg:y=\"12cm\" svg:width=\"18cm\" svg:height=\"10cm\"><draw:text-box>")+                for (note in slide.notes) serializeParagraph(body, note, styles, paraStyles, "text:p")+                body.append("</draw:text-box></draw:frame></presentation:notes>")+            }             body.append("</draw:page>")         }-        return buildDocument("office:presentation", styles, paraStyles, LinkedHashMap(), LinkedHashMap(), graphicStyles, body.toString())+        return buildDocument("office:presentation", styles, paraStyles, LinkedHashMap(), LinkedHashMap(), graphicStyles, body.toString(), drawPageStyles)     }      private fun serializeParagraph(         sb: StringBuilder, para: OdfParagraph,         styles: MutableMap<String, SpanStyleDef>,         paraStyles: MutableMap<String, ParaStyleDef>,-        tag: String+        tag: String,+        leadingBookmarks: List<String> = emptyList()     ) {         sb.append("<$tag")         val pStyleName = getOrCreateParaStyle(para, paraStyles)@@ -193,10 +243,19 @@ object OdfSerializer {             sb.append(""" text:outline-level="$level"""")         }         sb.append(">")+        for (name in leadingBookmarks) sb.append("""<text:bookmark text:name="${esc(name)}"/>""")         for (span in para.spans) {-            if (span.annotation != null) continue+            if (span.annotation != null) {+                // Serialize comments as office:annotation so they round-trip. (B3)+                sb.append("<office:annotation>")+                span.annotation.author?.let { sb.append("<dc:creator>${esc(it)}</dc:creator>") }+                span.annotation.date?.let { sb.append("<dc:date>${esc(it)}</dc:date>") }+                for (p in span.annotation.paragraphs) serializeParagraph(sb, p, styles, paraStyles, "text:p")+                sb.append("</office:annotation>")+                continue+            }             val needsStyle = span.bold || span.italic || span.underline || span.strikethrough ||-                span.color != null || span.fontSize != null || span.superscript || span.subscript+                span.color != null || span.fontSize != null || span.superscript || span.subscript || span.fontFamily != null             if (span.href != null) {                 sb.append("""<text:a xlink:href="${esc(span.href)}" xlink:type="simple">""")                 if (needsStyle) {@@ -242,24 +301,83 @@ object OdfSerializer {         sb.append("</table:table>")     } -    private fun serializeImageRef(sb: StringBuilder, image: OdfImage) {-        if (image.path == "inline") return+    private fun serializeImageRef(sb: StringBuilder, image: OdfImage, graphicStyles: MutableMap<String, GraphicStyleDef>, ctx: SerCtx) {+        val href = resolveImageHref(image, ctx) ?: run {+            if (!ctx.flat) return+            // Flat export with no path: emit base64 binary-data.+            sb.append("""<draw:frame""")+            if (image.width > 0) sb.append(""" svg:width="${cm(image.width)}"""")+            if (image.height > 0) sb.append(""" svg:height="${cm(image.height)}"""")+            appendRotation(sb, image)+            sb.append("""><draw:image><office:binary-data>${android.util.Base64.encodeToString(image.imageData, android.util.Base64.NO_WRAP)}</office:binary-data></draw:image></draw:frame>""")+            return+        }         sb.append("""<draw:frame""")-        if (image.width > 0) sb.append(""" svg:width="${image.width / 37.8f}cm"""")-        if (image.height > 0) sb.append(""" svg:height="${image.height / 37.8f}cm"""")-        appendClip(sb, image)-        sb.append("""><draw:image xlink:href="${esc(image.path)}" xlink:type="simple" xlink:actuate="onLoad"/>""")+        getOrCreateGraphicStyle(null, null, null, clipString(image), graphicStyles)?.let { sb.append(""" draw:style-name="$it"""") }+        if (image.width > 0) sb.append(""" svg:width="${cm(image.width)}"""")+        if (image.height > 0) sb.append(""" svg:height="${cm(image.height)}"""")+        appendRotation(sb, image)+        sb.append("""><draw:image xlink:href="${esc(href)}" xlink:type="simple" xlink:actuate="onLoad"/>""")         sb.append("</draw:frame>")     } -    /** Emits a non-standard percentage fo:clip so crop insets round-trip in this app; other suites render uncropped. (Phase 5) */-    private fun appendClip(sb: StringBuilder, image: OdfImage) {-        if (image.cropLeftPct > 0f || image.cropTopPct > 0f || image.cropRightPct > 0f || image.cropBottomPct > 0f) {-            fun p(v: Float) = "${v * 100f}%"-            sb.append(""" fo:clip="rect(${p(image.cropTopPct)} ${p(image.cropRightPct)} ${p(image.cropBottomPct)} ${p(image.cropLeftPct)})"""")+    /** Resolves the package href for an image, promoting inline images to the package. (A6) */+    private fun resolveImageHref(image: OdfImage, ctx: SerCtx): String? {+        if (image.path != "inline" && image.path.isNotBlank()) return image.path+        if (image.imageData.isEmpty()) return null+        if (ctx.flat) return null+        val path = ctx.nextImagePath(sniffExt(image.imageData))+        ctx.images[path] = image.imageData+        ctx.manifest[path] = mediaTypeForImage(path)+        return path+    }++    /** ODF fo:clip="rect(top right bottom left)" with absolute cm lengths relative to the natural image size. (A7) */+    private fun clipString(image: OdfImage): String? {+        if (image.cropLeftPct <= 0f && image.cropTopPct <= 0f && image.cropRightPct <= 0f && image.cropBottomPct <= 0f) return null+        val wPx = if (image.naturalWidthPx > 0f) image.naturalWidthPx else image.width+        val hPx = if (image.naturalHeightPx > 0f) image.naturalHeightPx else image.height+        if (wPx <= 0f || hPx <= 0f) return null+        val top = cm(image.cropTopPct * hPx)+        val right = cm(image.cropRightPct * wPx)+        val bottom = cm(image.cropBottomPct * hPx)+        val left = cm(image.cropLeftPct * wPx)+        return "rect($top $right $bottom $left)"+    }++    private fun appendRotation(sb: StringBuilder, image: OdfImage) {+        if (image.rotationDegrees != 0f) {+            // ODF rotation is counter-clockwise radians; our model stores clockwise degrees. (B1)+            val rad = (-image.rotationDegrees.toDouble() * Math.PI / 180.0)+            sb.append(""" draw:transform="rotate(${String.format(Locale.US, "%.5f", rad)})"""")         }     } +    private fun serializeChartFrame(+        sb: StringBuilder, chart: OdfChart, x: Float, y: Float, w: Float, h: Float, anchor: String,+        styles: MutableMap<String, SpanStyleDef>, paraStyles: MutableMap<String, ParaStyleDef>, ctx: SerCtx+    ) {+        if (ctx.flat) {+            // Flat export: best-effort text summary.+            sb.append("<draw:frame")+            if (anchor.isNotEmpty()) sb.append(""" text:anchor-type="$anchor"""")+            sb.append(""" svg:width="${cm(w)}" svg:height="${cm(h)}"><draw:text-box>""")+            serializeParagraph(sb, OdfParagraph(listOf(OdfSpan(text = chartSummary(chart)))), styles, paraStyles, "text:p")+            sb.append("</draw:text-box></draw:frame>")+            return+        }+        val dir = ctx.nextObjectDir()+        ctx.objects["$dir/content.xml"] = generateChartXml(chart, w, h)+        ctx.manifest["$dir/"] = "application/vnd.oasis.opendocument.chart"+        ctx.manifest["$dir/content.xml"] = "text/xml"+        sb.append("<draw:frame")+        if (anchor.isNotEmpty()) sb.append(""" text:anchor-type="$anchor"""")+        if (x != 0f || y != 0f) sb.append(""" svg:x="${cm(x)}" svg:y="${cm(y)}"""")+        sb.append(""" svg:width="${cm(w)}" svg:height="${cm(h)}">""")+        sb.append("""<draw:object xlink:href="./$dir" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>""")+        sb.append("</draw:frame>")+    }+     private fun chartSummary(chart: OdfChart): String {         val series = chart.series.joinToString(", ") { it.name }         return "[Chart: ${chart.type.name.lowercase()}] ${chart.title ?: ""} ${if (series.isNotEmpty()) "($series)" else ""}".trim()@@ -269,22 +387,28 @@ object OdfSerializer {         sb: StringBuilder, frame: OdfFrame,         styles: MutableMap<String, SpanStyleDef>,         paraStyles: MutableMap<String, ParaStyleDef>,-        graphicStyles: MutableMap<String, GraphicStyleDef>+        graphicStyles: MutableMap<String, GraphicStyleDef>,+        ctx: SerCtx     ) {+        // Charts become embedded objects in a frame of their own. (A8)+        if (frame.chart != null) {+            serializeChartFrame(sb, frame.chart, frame.x, frame.y, frame.width, frame.height, "", styles, paraStyles, ctx)+            return+        }         sb.append("<draw:frame")-        getOrCreateGraphicStyle(frame.fillColor, frame.strokeColor, frame.strokeWidth, graphicStyles)?.let { sb.append(""" draw:style-name="$it"""") }-        sb.append(""" svg:x="${frame.x / 37.8f}cm" svg:y="${frame.y / 37.8f}cm""")-        sb.append(""" svg:width="${frame.width / 37.8f}cm" svg:height="${frame.height / 37.8f}cm"""")-        if (frame.image != null) appendClip(sb, frame.image)+        val clip = frame.image?.let { clipString(it) }+        getOrCreateGraphicStyle(frame.fillColor, frame.strokeColor, frame.strokeWidth, clip, graphicStyles)?.let { sb.append(""" draw:style-name="$it"""") }+        sb.append(""" svg:x="${cm(frame.x)}" svg:y="${cm(frame.y)}"""")+        sb.append(""" svg:width="${cm(frame.width)}" svg:height="${cm(frame.height)}"""")+        frame.image?.let { appendRotation(sb, it) }         sb.append(">")-        if (frame.image != null && frame.image.path != "inline") {-            sb.append("""<draw:image xlink:href="${esc(frame.image.path)}" xlink:type="simple"/>""")-        }-        if (frame.chart != null) {-            // Simplified chart persistence: a text summary so other suites show something. (Phase 5)-            sb.append("<draw:text-box>")-            serializeParagraph(sb, OdfParagraph(listOf(OdfSpan(text = chartSummary(frame.chart)))), styles, paraStyles, "text:p")-            sb.append("</draw:text-box>")+        if (frame.image != null) {+            val href = resolveImageHref(frame.image, ctx)+            if (href != null) {+                sb.append("""<draw:image xlink:href="${esc(href)}" xlink:type="simple"/>""")+            } else if (ctx.flat && frame.image.imageData.isNotEmpty()) {+                sb.append("""<draw:image><office:binary-data>${android.util.Base64.encodeToString(frame.image.imageData, android.util.Base64.NO_WRAP)}</office:binary-data></draw:image>""")+            }         }         if (frame.paragraphs.isNotEmpty()) {             sb.append("<draw:text-box>")@@ -307,55 +431,139 @@ object OdfSerializer {             is OdfShape.CustomShape -> "draw:custom-shape"         }         sb.append("<$tag")-        getOrCreateGraphicStyle(shape.fillColor, shape.strokeColor, shape.strokeWidth, graphicStyles)?.let { sb.append(""" draw:style-name="$it"""") }-        sb.append(""" svg:x="${shape.x / 37.8f}cm" svg:y="${shape.y / 37.8f}cm""")-        sb.append(""" svg:width="${shape.width / 37.8f}cm" svg:height="${shape.height / 37.8f}cm"""")+        getOrCreateGraphicStyle(shape.fillColor, shape.strokeColor, shape.strokeWidth, null, graphicStyles)?.let { sb.append(""" draw:style-name="$it"""") }+        if (shape is OdfShape.Line) {+            // Lines use endpoint coordinates, not a bounding box. (A5)+            val x2 = if (shape.x2 != 0f || shape.y2 != 0f) shape.x2 else shape.x + shape.width+            val y2 = if (shape.x2 != 0f || shape.y2 != 0f) shape.y2 else shape.y + shape.height+            sb.append(""" svg:x1="${cm(shape.x)}" svg:y1="${cm(shape.y)}"""")+            sb.append(""" svg:x2="${cm(x2)}" svg:y2="${cm(y2)}"""")+        } else {+            sb.append(""" svg:x="${cm(shape.x)}" svg:y="${cm(shape.y)}"""")+            sb.append(""" svg:width="${cm(shape.width)}" svg:height="${cm(shape.height)}"""")+        }         sb.append(">")         for (para in shape.text) serializeParagraph(sb, para, styles, paraStyles, "text:p")         sb.append("</$tag>")     } +    // --- Embedded chart object generation (A8) ---++    private fun generateChartXml(chart: OdfChart, wPx: Float, hPx: Float): String {+        val chartClass = when (chart.type) {+            ChartType.LINE -> "chart:line"+            ChartType.PIE -> "chart:circle"+            ChartType.DONUT -> "chart:ring"+            ChartType.AREA -> "chart:area"+            ChartType.SCATTER -> "chart:scatter"+            else -> "chart:bar"+        }+        val rowCount = chart.categories.size+        val lastRow = rowCount + 1 // header is row 1+        val sb = StringBuilder()+        sb.append("""<?xml version="1.0" encoding="UTF-8"?>""")+        sb.append("""<office:document-content""")+        sb.append(""" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"""")+        sb.append(""" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0"""")+        sb.append(""" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"""")+        sb.append(""" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"""")+        sb.append(""" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"""")+        sb.append(""" xmlns:xlink="http://www.w3.org/1999/xlink"""")+        sb.append(""" office:version="1.3">""")+        sb.append("<office:body><office:chart>")+        sb.append("""<chart:chart chart:class="$chartClass" svg:width="${cm(wPx)}" svg:height="${cm(hPx)}">""")+        chart.title?.let { sb.append("""<chart:title><text:p>${esc(it)}</text:p></chart:title>""") }+        sb.append("<chart:plot-area>")+        sb.append("""<chart:axis chart:dimension="x" chart:name="primary-x"/>""")+        sb.append("""<chart:axis chart:dimension="y" chart:name="primary-y"/>""")+        chart.series.forEachIndexed { i, s ->+            val col = columnLetter(i + 1) // series start at column B+            sb.append("""<chart:series chart:values-cell-range-address="local-table.${'$'}$col${'$'}2:.${'$'}$col${'$'}$lastRow" chart:label-cell-address="local-table.${'$'}$col${'$'}1" chart:class="$chartClass">""")+            if (i == 0) sb.append("""<chart:categories table:cell-range-address="local-table.${'$'}A${'$'}2:.${'$'}A${'$'}$lastRow"/>""")+            sb.append("</chart:series>")+        }+        sb.append("</chart:plot-area>")+        // local-table mirroring categories + series values.+        sb.append("""<table:table table:name="local-table">""")+        sb.append("<table:table-header-rows><table:table-row><table:table-cell/>")+        for (s in chart.series) sb.append("""<table:table-cell office:value-type="string"><text:p>${esc(s.name)}</text:p></table:table-cell>""")+        sb.append("</table:table-row></table:table-header-rows>")+        sb.append("<table:table-rows>")+        for (r in 0 until rowCount) {+            sb.append("<table:table-row>")+            sb.append("""<table:table-cell office:value-type="string"><text:p>${esc(chart.categories[r])}</text:p></table:table-cell>""")+            for (s in chart.series) {+                val v = s.values.getOrNull(r) ?: 0f+                sb.append("""<table:table-cell office:value-type="float" office:value="$v"><text:p>$v</text:p></table:table-cell>""")+            }+            sb.append("</table:table-row>")+        }+        sb.append("</table:table-rows></table:table>")+        sb.append("</chart:chart></office:chart></office:body></office:document-content>")+        return sb.toString()+    }++    private fun columnLetter(index: Int): String {+        val sb = StringBuilder(); var n = index+        do { sb.insert(0, ('A' + n % 26)); n = n / 26 - 1 } while (n >= 0)+        return sb.toString()+    }+     // --- Style management ---      private data class SpanStyleDef(         val bold: Boolean = false, val italic: Boolean = false,         val underline: Boolean = false, val strikethrough: Boolean = false,         val color: Long? = null, val fontSize: Float? = null,-        val superscript: Boolean = false, val subscript: Boolean = false+        val superscript: Boolean = false, val subscript: Boolean = false,+        val fontFamily: String? = null     )      private data class ParaStyleDef(         val alignment: TextAlign? = null,         val marginLeft: Float = 0f,+        val marginTop: Float = 0f,+        val marginBottom: Float = 0f,         val textIndent: Float = 0f,         val lineHeightPercent: Float? = null,         val borderColor: Long? = null,-        val backgroundColor: Long? = null+        val backgroundColor: Long? = null,+        val breakBefore: Boolean = false,+        val tabStops: List<Float> = emptyList()     )      private data class CellStyleDef(         val backgroundColor: Long? = null, val textColor: Long? = null,         val bold: Boolean = false, val italic: Boolean = false,-        val alignment: TextAlign? = null, val borderColor: Long? = null+        val alignment: TextAlign? = null, val borderColor: Long? = null,+        val wrap: Boolean = false, val numberFormat: OdfNumberFormat? = null     )      private data class GraphicStyleDef(-        val fillColor: Long? = null, val strokeColor: Long? = null, val strokeWidth: Float? = null+        val fillColor: Long? = null, val strokeColor: Long? = null, val strokeWidth: Float? = null,+        val clip: String? = null     ) -    private fun getOrCreateGraphicStyle(fillColor: Long?, strokeColor: Long?, strokeWidth: Float?, styles: MutableMap<String, GraphicStyleDef>): String? {-        if (fillColor == null && strokeColor == null && strokeWidth == null) return null-        val def = GraphicStyleDef(fillColor, strokeColor, strokeWidth)+    private fun getOrCreateGraphicStyle(fillColor: Long?, strokeColor: Long?, strokeWidth: Float?, clip: String?, styles: MutableMap<String, GraphicStyleDef>): String? {+        if (fillColor == null && strokeColor == null && strokeWidth == null && clip == null) return null+        val def = GraphicStyleDef(fillColor, strokeColor, strokeWidth, clip)         for ((name, existing) in styles) if (existing == def) return name         val name = "gr${styles.size + 1}"         styles[name] = def         return name     } +    private fun getOrCreateDrawPageStyle(fillColor: Long, styles: MutableMap<String, Long>): String {+        for ((name, existing) in styles) if (existing == fillColor) return name+        val name = "dp${styles.size + 1}"+        styles[name] = fillColor+        return name+    }+     private fun getOrCreateCellStyle(cell: OdfCell, styles: MutableMap<String, CellStyleDef>): String? {         if (cell.backgroundColor == null && cell.textColor == null && !cell.bold && !cell.italic &&-            cell.alignment == null && cell.borderColor == null) return null-        val def = CellStyleDef(cell.backgroundColor, cell.textColor, cell.bold, cell.italic, cell.alignment, cell.borderColor)+            cell.alignment == null && cell.borderColor == null && !cell.wrap && cell.numberFormat == null) return null+        val def = CellStyleDef(cell.backgroundColor, cell.textColor, cell.bold, cell.italic, cell.alignment, cell.borderColor, cell.wrap, cell.numberFormat)         for ((name, existing) in styles) if (existing == def) return name         val name = "ce${styles.size + 1}"         styles[name] = def@@ -371,7 +579,7 @@ object OdfSerializer {      private fun getOrCreateSpanStyle(span: OdfSpan, styles: MutableMap<String, SpanStyleDef>): String {         val def = SpanStyleDef(span.bold, span.italic, span.underline, span.strikethrough,-            span.color, span.fontSize, span.superscript, span.subscript)+            span.color, span.fontSize, span.superscript, span.subscript, span.fontFamily)         for ((name, existing) in styles) if (existing == def) return name         val name = "T${styles.size + 1}"         styles[name] = def@@ -380,9 +588,11 @@ object OdfSerializer {      private fun getOrCreateParaStyle(para: OdfParagraph, styles: MutableMap<String, ParaStyleDef>): String? {         val hasProps = para.alignment != null || para.marginLeft != 0f || para.textIndent != 0f ||-            para.lineHeightPercent != null || para.borderColor != null || para.backgroundColor != null-        if (!hasProps) return null-        val def = ParaStyleDef(para.alignment, para.marginLeft, para.textIndent, para.lineHeightPercent, para.borderColor, para.backgroundColor)+            para.lineHeightPercent != null || para.borderColor != null || para.backgroundColor != null ||+            para.marginTop != 0f || para.marginBottom != 0f || para.tabStops.isNotEmpty()+        if (!hasProps && !para.breakBeforePage) return null+        val def = ParaStyleDef(para.alignment, para.marginLeft, para.marginTop, para.marginBottom, para.textIndent,+            para.lineHeightPercent, para.borderColor, para.backgroundColor, para.breakBeforePage, para.tabStops)         for ((name, existing) in styles) if (existing == def) return name         val name = "P${styles.size + 1}"         styles[name] = def@@ -398,7 +608,8 @@ object OdfSerializer {         cellStyles: Map<String, CellStyleDef>,         colStyles: Map<String, Float>,         graphicStyles: Map<String, GraphicStyleDef>,-        bodyContent: String+        bodyContent: String,+        drawPageStyles: Map<String, Long> = emptyMap()     ): String {         val sb = StringBuilder()         sb.append("""<?xml version="1.0" encoding="UTF-8"?>""")@@ -411,6 +622,9 @@ object OdfSerializer {         sb.append(""" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"""")         sb.append(""" xmlns:xlink="http://www.w3.org/1999/xlink"""")         sb.append(""" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"""")+        sb.append(""" xmlns:dc="http://purl.org/dc/elements/1.1/"""")+        sb.append(""" xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"""")+        sb.append(""" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"""")         sb.append(""" office:version="1.3">""")          sb.append("<office:automatic-styles>")@@ -422,6 +636,7 @@ object OdfSerializer {             if (def.strikethrough) sb.append(""" style:text-line-through-style="solid"""")             if (def.color != null) sb.append(""" fo:color="${formatColor(def.color)}"""")             if (def.fontSize != null) sb.append(""" fo:font-size="${def.fontSize}pt"""")+            if (def.fontFamily != null) sb.append(""" style:font-name="${esc(def.fontFamily)}"""")             if (def.superscript) sb.append(""" style:text-position="super 58%"""")             if (def.subscript) sb.append(""" style:text-position="sub 58%"""")             sb.append("/></style:style>")@@ -435,21 +650,46 @@ object OdfSerializer {                 TextAlign.Justify -> sb.append(""" fo:text-align="justify"""")                 else -> {}             }-            if (def.marginLeft != 0f) sb.append(""" fo:margin-left="${def.marginLeft / 37.8f}cm"""")-            if (def.textIndent != 0f) sb.append(""" fo:text-indent="${def.textIndent / 37.8f}cm"""")+            if (def.marginLeft != 0f) sb.append(""" fo:margin-left="${cm(def.marginLeft)}"""")+            if (def.marginTop != 0f) sb.append(""" fo:margin-top="${cm(def.marginTop)}"""")+            if (def.marginBottom != 0f) sb.append(""" fo:margin-bottom="${cm(def.marginBottom)}"""")+            if (def.textIndent != 0f) sb.append(""" fo:text-indent="${cm(def.textIndent)}"""")             if (def.lineHeightPercent != null) sb.append(""" fo:line-height="${(def.lineHeightPercent * 100).toInt()}%"""")             if (def.borderColor != null) sb.append(""" fo:border="0.5pt solid ${formatColor(def.borderColor)}"""")             if (def.backgroundColor != null) sb.append(""" fo:background-color="${formatColor(def.backgroundColor)}"""")+            if (def.breakBefore) sb.append(""" fo:break-before="page"""")+            if (def.tabStops.isNotEmpty()) {+                sb.append("><style:tab-stops>")+                for (t in def.tabStops) sb.append("""<style:tab-stop style:position="${cm(t)}"/>""")+                sb.append("</style:tab-stops>")+                sb.append("</style:paragraph-properties></style:style>")+                continue+            }             sb.append("/></style:style>")         }         for ((name, width) in colStyles) {-            sb.append("""<style:style style:name="$name" style:family="table-column"><style:table-column-properties style:column-width="${width / 37.8f}cm"/></style:style>""")+            sb.append("""<style:style style:name="$name" style:family="table-column"><style:table-column-properties style:column-width="${cm(width)}"/></style:style>""")+        }+        // Number/date/currency data styles for cells, emitted before the cell styles that reference them. (B6)+        val dataStyleNames = HashMap<String, String>()+        run {+            var n = 0+            for ((cellName, def) in cellStyles) {+                val fmt = def.numberFormat ?: continue+                n+++                val dsName = "N$n"+                dataStyleNames[cellName] = dsName+                sb.append(numberStyleXml(dsName, fmt))+            }         }         for ((name, def) in cellStyles) {-            sb.append("""<style:style style:name="$name" style:family="table-cell">""")+            sb.append("""<style:style style:name="$name" style:family="table-cell"""")+            dataStyleNames[name]?.let { sb.append(""" style:data-style-name="$it"""") }+            sb.append(">")             sb.append("<style:table-cell-properties")             if (def.backgroundColor != null) sb.append(""" fo:background-color="${formatColor(def.backgroundColor)}"""")             if (def.borderColor != null) sb.append(""" fo:border="0.5pt solid ${formatColor(def.borderColor)}"""")+            if (def.wrap) sb.append(""" fo:wrap-option="wrap"""")             sb.append("/>")             when (def.alignment) {                 TextAlign.Start, TextAlign.Left -> sb.append("""<style:paragraph-properties fo:text-align="start"/>""")@@ -469,9 +709,13 @@ object OdfSerializer {             if (def.fillColor != null) sb.append(""" draw:fill="solid" draw:fill-color="${formatColor(def.fillColor)}"""")             else sb.append(""" draw:fill="none"""")             if (def.strokeColor != null) sb.append(""" draw:stroke="solid" svg:stroke-color="${formatColor(def.strokeColor)}"""")-            if (def.strokeWidth != null) sb.append(""" svg:stroke-width="${def.strokeWidth / 37.8f}cm"""")+            if (def.strokeWidth != null) sb.append(""" svg:stroke-width="${cm(def.strokeWidth)}"""")+            if (def.clip != null) sb.append(""" fo:clip="${def.clip}"""")             sb.append("/></style:style>")         }+        for ((name, color) in drawPageStyles) {+            sb.append("""<style:style style:name="$name" style:family="drawing-page"><style:drawing-page-properties draw:fill="solid" draw:fill-color="${formatColor(color)}"/></style:style>""")+        }         sb.append("</office:automatic-styles>")          sb.append("<office:body><$bodyType>")@@ -481,11 +725,63 @@ object OdfSerializer {         return sb.toString()     } +    private fun numberStyleXml(name: String, fmt: OdfNumberFormat): String {+        val sb = StringBuilder()+        val dec = fmt.decimals ?: 2+        when {+            fmt.isDate -> {+                sb.append("""<number:date-style style:name="$name">""")+                sb.append("""<number:year number:style="long"/><number:text>-</number:text>""")+                sb.append("""<number:month number:style="long"/><number:text>-</number:text>""")+                sb.append("""<number:day number:style="long"/>""")+                sb.append("</number:date-style>")+            }+            fmt.currencySymbol != null -> {+                sb.append("""<number:currency-style style:name="$name">""")+                sb.append("""<number:currency-symbol>${esc(fmt.currencySymbol)}</number:currency-symbol>""")+                sb.append("""<number:number number:decimal-places="$dec" number:min-integer-digits="1"${if (fmt.grouping) " number:grouping=\"true\"" else ""}/>""")+                sb.append("</number:currency-style>")+            }+            fmt.percent -> {+                sb.append("""<number:percentage-style style:name="$name">""")+                sb.append("""<number:number number:decimal-places="$dec" number:min-integer-digits="1"/>""")+                sb.append("""<number:text>%</number:text>""")+                sb.append("</number:percentage-style>")+            }+            else -> {+                sb.append("""<number:number-style style:name="$name">""")+                sb.append("""<number:number number:decimal-places="$dec" number:min-integer-digits="1"${if (fmt.grouping) " number:grouping=\"true\"" else ""}/>""")+                sb.append("</number:number-style>")+            }+        }+        return sb.toString()+    }+     private fun formatColor(color: Long): String {         val rgb = (color and 0xFFFFFFL).toInt()         return String.format("#%06X", rgb)     } +    /** px@96 -> cm length string. */+    private fun cm(px: Float): String = String.format(Locale.US, "%.4fcm", px / 37.795f)++    private fun sniffExt(bytes: ByteArray): String = when {+        bytes.size >= 3 && bytes[0] == 0x89.toByte() && bytes[1] == 'P'.code.toByte() && bytes[2] == 'N'.code.toByte() -> "png"+        bytes.size >= 2 && bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() -> "jpg"+        bytes.size >= 3 && bytes[0] == 'G'.code.toByte() && bytes[1] == 'I'.code.toByte() && bytes[2] == 'F'.code.toByte() -> "gif"+        else -> "png"+    }++    private fun mediaTypeForImage(path: String): String = when (path.substringAfterLast('.').lowercase()) {+        "png" -> "image/png"+        "jpg", "jpeg" -> "image/jpeg"+        "gif" -> "image/gif"+        "bmp" -> "image/bmp"+        "svg" -> "image/svg+xml"+        "webp" -> "image/webp"+        else -> "image/png"+    }+     private fun esc(text: String): String = text         .replace("&", "&amp;")         .replace("<", "&lt;")
office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.ktindex d591679581..a09c0a58ba 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt@@ -10,10 +10,13 @@ import java.util.zip.ZipOutputStream object OdfWriter {      fun save(context: Context, sourceUri: Uri, document: OdfDocument, targetUri: Uri) {-        val contentXml = OdfSerializer.serialize(document)+        val result = OdfSerializer.serializePackaged(document)+        val contentXml = result.contentXml         val metaXml = OdfSerializer.serializeMeta(document.metadata)         val docImages = imagesOf(document)         val written = mutableSetOf<String>()+        // Media types for generated package parts (embedded chart objects, inline images).+        val extraManifest = LinkedHashMap<String, String>(result.manifest)          val buffer = ByteArrayOutputStream()         ZipOutputStream(buffer).use { zipOut ->@@ -21,41 +24,49 @@ object OdfWriter {                 ZipInputStream(input).use { zipIn ->                     var entry = zipIn.nextEntry                     while (entry != null) {-                        if (entry.name == "content.xml") {-                            zipOut.putNextEntry(ZipEntry("content.xml"))-                            zipOut.write(contentXml.toByteArray(Charsets.UTF_8))-                            zipOut.closeEntry()-                            written.add("content.xml")-                        } else if (entry.name == "meta.xml") {-                            zipOut.putNextEntry(ZipEntry("meta.xml"))-                            zipOut.write(metaXml.toByteArray(Charsets.UTF_8))-                            zipOut.closeEntry()-                            written.add("meta.xml")-                        } else if (!entry.isDirectory) {-                            zipOut.putNextEntry(ZipEntry(entry.name))-                            zipIn.copyTo(zipOut)-                            zipOut.closeEntry()-                            written.add(entry.name)+                        val name = entry.name+                        when {+                            name == "content.xml" -> {+                                writeEntry(zipOut, "content.xml", contentXml.toByteArray(Charsets.UTF_8)); written.add(name)+                            }+                            name == "meta.xml" -> {+                                writeEntry(zipOut, "meta.xml", metaXml.toByteArray(Charsets.UTF_8)); written.add(name)+                            }+                            // Regenerated below; never copy the old manifest.+                            name == "META-INF/manifest.xml" -> {}+                            !entry.isDirectory -> {+                                zipOut.putNextEntry(ZipEntry(name)); zipIn.copyTo(zipOut); zipOut.closeEntry(); written.add(name)+                            }                         }                         entry = zipIn.nextEntry                     }                 }             }-            // If the source had no content.xml (e.g. brand-new flat/empty), ensure one is written.             if ("content.xml" !in written) {-                zipOut.putNextEntry(ZipEntry("content.xml"))-                zipOut.write(contentXml.toByteArray(Charsets.UTF_8))-                zipOut.closeEntry()-                written.add("content.xml")+                writeEntry(zipOut, "content.xml", contentXml.toByteArray(Charsets.UTF_8)); written.add("content.xml")             }-            // Write any newly-inserted images that weren't part of the original package. (K72/K73)+            if ("meta.xml" !in written) {+                writeEntry(zipOut, "meta.xml", metaXml.toByteArray(Charsets.UTF_8)); written.add("meta.xml")+            }+            // Document images (inserted via the editor) not already in the package. (A6)             for ((path, bytes) in docImages) {-                if (path == "inline" || path in written || bytes.isEmpty()) continue-                zipOut.putNextEntry(ZipEntry(path))-                zipOut.write(bytes)-                zipOut.closeEntry()-                written.add(path)+                if (path == "inline" || path.isBlank() || path in written || bytes.isEmpty()) continue+                writeEntry(zipOut, path, bytes); written.add(path)+                extraManifest[path] = mediaTypeFor(path, document)+            }+            // Inline images promoted to the package during serialization. (A6)+            for ((path, bytes) in result.images) {+                if (path in written || bytes.isEmpty()) continue+                writeEntry(zipOut, path, bytes); written.add(path)             }+            // Embedded chart objects. (A8)+            for ((path, xml) in result.objects) {+                if (path in written) continue+                writeEntry(zipOut, path, xml.toByteArray(Charsets.UTF_8)); written.add(path)+            }+            // Regenerate META-INF/manifest.xml listing everything actually in the package.+            val manifestXml = buildManifest(document, written, extraManifest)+            writeEntry(zipOut, "META-INF/manifest.xml", manifestXml.toByteArray(Charsets.UTF_8))         }          context.contentResolver.openOutputStream(targetUri, "wt")?.use { output ->@@ -63,6 +74,59 @@ object OdfWriter {         }     } +    private fun writeEntry(zipOut: ZipOutputStream, name: String, bytes: ByteArray) {+        zipOut.putNextEntry(ZipEntry(name))+        zipOut.write(bytes)+        zipOut.closeEntry()+    }++    /** Rebuilds META-INF/manifest.xml from the final package contents so new images/objects are declared. (A6/A8) */+    private fun buildManifest(document: OdfDocument, written: Set<String>, extra: Map<String, String>): String {+        val mime = documentMime(document)+        val sb = StringBuilder()+        sb.append("""<?xml version="1.0" encoding="UTF-8"?>""")+        sb.append("""<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">""")+        sb.append("""<manifest:file-entry manifest:full-path="/" manifest:version="1.3" manifest:media-type="$mime"/>""")+        // Embedded-object directory entries (declared first so readers register the sub-documents).+        for ((path, type) in extra) {+            if (path.endsWith("/")) sb.append("""<manifest:file-entry manifest:full-path="$path" manifest:media-type="$type"/>""")+        }+        val seen = mutableSetOf("/")+        fun add(path: String, type: String) {+            if (path in seen) return+            seen.add(path)+            sb.append("""<manifest:file-entry manifest:full-path="$path" manifest:media-type="$type"/>""")+        }+        for ((path, type) in extra) if (!path.endsWith("/")) add(path, type)+        for (path in written) {+            if (path == "mimetype" || path == "META-INF/manifest.xml") continue+            add(path, mediaTypeFor(path, document))+        }+        sb.append("</manifest:manifest>")+        return sb.toString()+    }++    private fun documentMime(document: OdfDocument): String = when (document) {+        is OdfDocument.TextDocument -> "application/vnd.oasis.opendocument.text"+        is OdfDocument.Spreadsheet -> "application/vnd.oasis.opendocument.spreadsheet"+        is OdfDocument.Presentation -> "application/vnd.oasis.opendocument.presentation"+        is OdfDocument.Drawing -> "application/vnd.oasis.opendocument.graphics"+    }++    private fun mediaTypeFor(path: String, document: OdfDocument): String = when {+        path == "content.xml" || path == "styles.xml" || path == "meta.xml" || path == "settings.xml" -> "text/xml"+        path.endsWith("/content.xml") || path.endsWith("/styles.xml") -> "text/xml"+        path.endsWith(".xml") -> "text/xml"+        path.endsWith(".rdf") -> "application/rdf+xml"+        path.endsWith(".png") -> "image/png"+        path.endsWith(".jpg") || path.endsWith(".jpeg") -> "image/jpeg"+        path.endsWith(".gif") -> "image/gif"+        path.endsWith(".bmp") -> "image/bmp"+        path.endsWith(".svg") -> "image/svg+xml"+        path.endsWith(".webp") -> "image/webp"+        else -> "application/octet-stream"+    }+     private fun imagesOf(document: OdfDocument): Map<String, ByteArray> = when (document) {         is OdfDocument.TextDocument -> document.images         is OdfDocument.Spreadsheet -> document.images
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 46e345241e..bde3925fa5 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt@@ -1272,6 +1272,10 @@ fun SpreadsheetView(     var renameText by remember { mutableStateOf("") }     var showSortDialog by remember { mutableStateOf(false) } +    // A3: keep the selected sheet/floating indices valid after undo/redo shrinks the lists.+    selectedSheet = selectedSheet.coerceIn(0, doc.sheets.size - 1)+    if (selectedFloating >= doc.sheets[selectedSheet].floating.size) selectedFloating = -1+     Column(modifier = Modifier.fillMaxSize()) {         if (doc.sheets.size > 1 || isEditMode) {             Row(verticalAlignment = Alignment.CenterVertically) {@@ -1338,64 +1342,72 @@ fun SpreadsheetView(             return w.dp         } -        Box(Modifier.fillMaxSize()) {+        // A1: anchor floating objects inside the scrolled grid content (rides both scroll axes).+        // Map model px@96 -> grid content dp by sizing the overlay to the content and passing the+        // content's dp dimensions as the reference space.+        val hScroll = rememberScrollState()+        var contentWidthDp = 40f+        for (col in 0 until maxCols) contentWidthDp += colWidthDp(col, 1).value+        val contentHeightDp = 26f + sheet.rows.size * 33f+         LazyColumn(modifier = Modifier.fillMaxSize()) {             item {-                Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp)) {-                    Column {-                        Row {-                            Box(Modifier.defaultMinSize(minWidth = 40.dp).background(MaterialTheme.colorScheme.surfaceVariant).border(0.5.dp, MaterialTheme.colorScheme.outline).padding(4.dp), contentAlignment = Alignment.Center) { Text("") }-                            for (col in 0 until maxCols) Box(Modifier.width(colWidthDp(col, 1)).background(MaterialTheme.colorScheme.surfaceVariant).border(0.5.dp, MaterialTheme.colorScheme.outline).padding(4.dp), contentAlignment = Alignment.Center) {-                                Text(columnLabel(col), style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)-                            }-                        }-                        for ((rowIdx, row) in sheet.rows.withIndex()) {-                            Row(Modifier.height(IntrinsicSize.Min)) {-                                Box(Modifier.defaultMinSize(minWidth = 40.dp).fillMaxHeight().background(MaterialTheme.colorScheme.surfaceVariant).border(0.5.dp, MaterialTheme.colorScheme.outline).padding(4.dp), contentAlignment = Alignment.Center) {-                                    Text("${rowIdx + 1}", style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)+                Row(Modifier.horizontalScroll(hScroll).padding(horizontal = 4.dp)) {+                    Box {+                        Column {+                            Row {+                                Box(Modifier.defaultMinSize(minWidth = 40.dp).background(MaterialTheme.colorScheme.surfaceVariant).border(0.5.dp, MaterialTheme.colorScheme.outline).padding(4.dp), contentAlignment = Alignment.Center) { Text("") }+                                for (col in 0 until maxCols) Box(Modifier.width(colWidthDp(col, 1)).background(MaterialTheme.colorScheme.surfaceVariant).border(0.5.dp, MaterialTheme.colorScheme.outline).padding(4.dp), contentAlignment = Alignment.Center) {+                                    Text(columnLabel(col), style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)                                 }-                                for ((cellIdx, cell) in row.cells.withIndex()) {-                                    if (cell.isCovered) continue-                                    val isEditing = editingCell?.let { it.first == selectedSheet && it.second == rowIdx && it.third == cellIdx } == true-                                    val isMatch = searchQuery.isNotEmpty() && cell.text.contains(searchQuery, ignoreCase = true)-                                    Box(-                                        Modifier.width(colWidthDp(cellIdx, cell.spannedColumns))-                                            .fillMaxHeight()-                                            .border(if (isEditing) 2.dp else 0.5.dp, if (isEditing) MaterialTheme.colorScheme.primary else (cell.borderColor?.let { Color(it.toInt()) } ?: MaterialTheme.colorScheme.outline))-                                            .then(if (isMatch) Modifier.background(Color(0xFFFFEB3B).copy(alpha = 0.3f)) else cell.backgroundColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)-                                            .then(if (isEditMode) Modifier.clickable { editingCell = Triple(selectedSheet, rowIdx, cellIdx); onCellSelected(selectedSheet, rowIdx, cellIdx); val t = cell.formula ?: cell.text; editText = TextFieldValue(t, TextRange(0, t.length)) } else Modifier)-                                            .padding(8.dp, 4.dp)-                                    ) {-                                        val displayText = OdfFormulaEngine.displayValue(sheet, rowIdx, cellIdx)-                                        val cellAlign = cell.alignment ?: if (OdfFormulaEngine.isNumeric(sheet, rowIdx, cellIdx)) TextAlign.End else null-                                        Text(displayText,-                                            style = MaterialTheme.typography.bodyMedium.let { if (fontSizeMultiplier != 1f && it.fontSize != TextUnit.Unspecified) it.copy(fontSize = it.fontSize * fontSizeMultiplier) else it },-                                            fontWeight = if (cell.bold) FontWeight.Bold else null,-                                            fontStyle = if (cell.italic) FontStyle.Italic else null,-                                            color = cell.textColor?.let { Color(it.toInt()) } ?: Color.Unspecified,-                                            textAlign = cellAlign, maxLines = if (cell.wrap) Int.MAX_VALUE else 3)+                            }+                            for ((rowIdx, row) in sheet.rows.withIndex()) {+                                Row(Modifier.height(IntrinsicSize.Min)) {+                                    Box(Modifier.defaultMinSize(minWidth = 40.dp).fillMaxHeight().background(MaterialTheme.colorScheme.surfaceVariant).border(0.5.dp, MaterialTheme.colorScheme.outline).padding(4.dp), contentAlignment = Alignment.Center) {+                                        Text("${rowIdx + 1}", style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)+                                    }+                                    for ((cellIdx, cell) in row.cells.withIndex()) {+                                        if (cell.isCovered) continue+                                        val isEditing = editingCell?.let { it.first == selectedSheet && it.second == rowIdx && it.third == cellIdx } == true+                                        val isMatch = searchQuery.isNotEmpty() && cell.text.contains(searchQuery, ignoreCase = true)+                                        Box(+                                            Modifier.width(colWidthDp(cellIdx, cell.spannedColumns))+                                                .fillMaxHeight()+                                                .border(if (isEditing) 2.dp else 0.5.dp, if (isEditing) MaterialTheme.colorScheme.primary else (cell.borderColor?.let { Color(it.toInt()) } ?: MaterialTheme.colorScheme.outline))+                                                .then(if (isMatch) Modifier.background(Color(0xFFFFEB3B).copy(alpha = 0.3f)) else cell.backgroundColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)+                                                .then(if (isEditMode) Modifier.clickable { editingCell = Triple(selectedSheet, rowIdx, cellIdx); selectedFloating = -1; onCellSelected(selectedSheet, rowIdx, cellIdx); val t = cell.formula ?: cell.text; editText = TextFieldValue(t, TextRange(0, t.length)) } else Modifier)+                                                .padding(8.dp, 4.dp)+                                        ) {+                                            val displayText = OdfFormulaEngine.displayValue(sheet, rowIdx, cellIdx)+                                            val cellAlign = cell.alignment ?: if (OdfFormulaEngine.isNumeric(sheet, rowIdx, cellIdx)) TextAlign.End else null+                                            Text(displayText,+                                                style = MaterialTheme.typography.bodyMedium.let { if (fontSizeMultiplier != 1f && it.fontSize != TextUnit.Unspecified) it.copy(fontSize = it.fontSize * fontSizeMultiplier) else it },+                                                fontWeight = if (cell.bold) FontWeight.Bold else null,+                                                fontStyle = if (cell.italic) FontStyle.Italic else null,+                                                color = cell.textColor?.let { Color(it.toInt()) } ?: Color.Unspecified,+                                                textAlign = cellAlign, maxLines = if (cell.wrap) Int.MAX_VALUE else 3)+                                        }                                     }                                 }                             }                         }+                        if (isEditMode || sheet.floating.isNotEmpty()) {+                            FloatingElementLayer(+                                elements = sheet.floating, refW = contentWidthDp, refH = contentHeightDp,+                                modifier = Modifier.matchParentSize(),+                                editMode = isEditMode, selectedIndex = selectedFloating,+                                keyPrefix = "sheet$selectedSheet", interactiveBackground = false,+                                onSelect = { selectedFloating = it },+                                onElementTextChange = { ei, t -> onFloatingTextChange(selectedSheet, ei, t) },+                                onBoundsChange = { ei, x, y, w, h -> onFloatingBoundsChange(selectedSheet, ei, x, y, w, h) },+                                onDelete = { ei -> onFloatingDelete(selectedSheet, ei); selectedFloating = -1 },+                                onCropImage = { ei -> onFloatingCrop(selectedSheet, ei) }+                            )+                        }                     }                 }             }         }-        if (isEditMode || sheet.floating.isNotEmpty()) {-            val rw = maxOf(1058f, sheet.floating.maxOfOrNull { val b = it.bounds(); b[0] + b[2] } ?: 0f)-            val rh = maxOf(794f, sheet.floating.maxOfOrNull { val b = it.bounds(); b[1] + b[3] } ?: 0f)-            FloatingElementLayer(-                elements = sheet.floating, refW = rw, refH = rh, editMode = isEditMode, selectedIndex = selectedFloating,-                keyPrefix = "sheet$selectedSheet", interactiveBackground = false,-                onSelect = { selectedFloating = it },-                onElementTextChange = { ei, t -> onFloatingTextChange(selectedSheet, ei, t) },-                onBoundsChange = { ei, x, y, w, h -> onFloatingBoundsChange(selectedSheet, ei, x, y, w, h) },-                onDelete = { ei -> onFloatingDelete(selectedSheet, ei); selectedFloating = -1 },-                onCropImage = { ei -> onFloatingCrop(selectedSheet, ei) }-            )-        }-        }     }      if (showRenameSheet) {@@ -1664,6 +1676,7 @@ fun FloatingElementLayer(     editMode: Boolean,     selectedIndex: Int,     keyPrefix: String,+    modifier: Modifier = Modifier.fillMaxSize(),     backgroundColor: Long? = null,     interactiveBackground: Boolean = true,     onSelect: (Int) -> Unit = {},@@ -1673,7 +1686,7 @@ fun FloatingElementLayer(     onCropImage: (Int) -> Unit = {} ) {     BoxWithConstraints(-        Modifier.fillMaxSize()+        modifier             .then(backgroundColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)             .then(if (editMode && interactiveBackground) Modifier.pointerInput(elements.size) { detectTapGestures { onSelect(-1) } } else Modifier)     ) {
office/src/main/java/com/vayunmathur/office/ui/OfficeBottomBar.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OfficeBottomBar.kt b/office/src/main/java/com/vayunmathur/office/ui/OfficeBottomBar.ktindex 9265b191fb..83bc379e28 100644--- a/office/src/main/java/com/vayunmathur/office/ui/OfficeBottomBar.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/OfficeBottomBar.kt@@ -68,7 +68,8 @@ data class BottomBarActions(     val onInsertShape: (ShapeKind) -> Unit = {},     val onInsertChart: () -> Unit = {},     val onInsertTable: () -> Unit = {},-    val onDeleteElement: () -> Unit = {}+    val onDeleteElement: () -> Unit = {},+    val onCellBorder: () -> Unit = {} )  @Composable@@ -265,6 +266,24 @@ private fun CellFormatControls(target: FormatTarget.Cell?, viewModel: OfficeView         }     }     TextButton(onClick = { if (enabled) viewModel.unmergeCells(s, r, c) }, enabled = enabled) { Text("Unmerge") }+    Box {+        var moreMenu by remember { mutableStateOf(false) }+        var numMenu by remember { mutableStateOf(false) }+        FmtIcon(R.drawable.more_vert_24px, false, enabled, "More") { moreMenu = true }+        DropdownMenu(expanded = moreMenu, onDismissRequest = { moreMenu = false }) {+            DropdownMenuItem(text = { Text("Fill down") }, enabled = enabled, onClick = { moreMenu = false; if (enabled) viewModel.fillDownToEnd(s, r, c) })+            DropdownMenuItem(text = { Text("Border color…") }, enabled = enabled, onClick = { moreMenu = false; actions.onCellBorder() })+            DropdownMenuItem(text = { Text("Number format") }, trailingIcon = { Icon(painterResource(R.drawable.arrow_drop_down_24px), null) }, enabled = enabled, onClick = { numMenu = true })+        }+        DropdownMenu(expanded = numMenu, onDismissRequest = { numMenu = false }) {+            DropdownMenuItem(text = { Text("General") }, onClick = { numMenu = false; moreMenu = false; if (enabled) viewModel.setCellNumberFormat(s, r, c, null) })+            DropdownMenuItem(text = { Text("Number (2 dp)") }, onClick = { numMenu = false; moreMenu = false; if (enabled) viewModel.setCellNumberFormat(s, r, c, OdfNumberFormat(decimals = 2, grouping = true)) })+            DropdownMenuItem(text = { Text("Integer") }, onClick = { numMenu = false; moreMenu = false; if (enabled) viewModel.setCellNumberFormat(s, r, c, OdfNumberFormat(decimals = 0)) })+            DropdownMenuItem(text = { Text("Percent") }, onClick = { numMenu = false; moreMenu = false; if (enabled) viewModel.setCellNumberFormat(s, r, c, OdfNumberFormat(decimals = 0, percent = true)) })+            DropdownMenuItem(text = { Text("Currency ($)") }, onClick = { numMenu = false; moreMenu = false; if (enabled) viewModel.setCellNumberFormat(s, r, c, OdfNumberFormat(decimals = 2, currencySymbol = "$", grouping = true)) })+            DropdownMenuItem(text = { Text("Date") }, onClick = { numMenu = false; moreMenu = false; if (enabled) viewModel.setCellNumberFormat(s, r, c, OdfNumberFormat(isDate = true)) })+        }+    } }  // --- Presentation element branch ---@@ -290,4 +309,14 @@ private fun ElementFormatControls(target: FormatTarget.Element?, viewModel: Offi         }     }     FmtIcon(com.vayunmathur.library.R.drawable.delete_24px, false, enabled, "Delete element") { if (enabled) actions.onDeleteElement() }+    Box {+        var moreMenu by remember { mutableStateOf(false) }+        FmtIcon(R.drawable.more_vert_24px, false, enabled, "More") { moreMenu = true }+        DropdownMenu(expanded = moreMenu, onDismissRequest = { moreMenu = false }) {+            DropdownMenuItem(text = { Text("Duplicate") }, enabled = enabled, onClick = { moreMenu = false; if (enabled) viewModel.duplicateSlideElement(s, e) })+            DropdownMenuItem(text = { Text("Bring to front") }, enabled = enabled, onClick = { moreMenu = false; if (enabled) viewModel.reorderSlideElement(s, e, true) })+            DropdownMenuItem(text = { Text("Send to back") }, enabled = enabled, onClick = { moreMenu = false; if (enabled) viewModel.reorderSlideElement(s, e, false) })+            DropdownMenuItem(text = { Text("Rotate 90°") }, enabled = enabled, onClick = { moreMenu = false; if (enabled) viewModel.rotateSlideImage(s, e, 90f) })+        }+    } }
office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.ktindex 857498e42f..648b008194 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -36,6 +36,11 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     private val _nightMode = MutableStateFlow(false)     val nightMode: StateFlow<Boolean> = _nightMode +    // Incremented whenever the document changes shape via undo/redo so the UI can+    // reset/clamp hoisted selection state (active cell/slide/element). (A4)+    private val _selectionInvalidation = MutableStateFlow(0)+    val selectionInvalidation: StateFlow<Int> = _selectionInvalidation+     var documentUri: Uri? = null         private set @@ -111,6 +116,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         _canUndo.value = undoStack.isNotEmpty()         _canRedo.value = redoStack.isNotEmpty()         _hasUnsavedChanges.value = true+        _selectionInvalidation.value++     }      fun redo() {@@ -121,6 +127,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         _canUndo.value = undoStack.isNotEmpty()         _canRedo.value = redoStack.isNotEmpty()         _hasUnsavedChanges.value = true+        _selectionInvalidation.value++     }      private fun updateDocument(newDoc: OdfDocument) {@@ -544,14 +551,27 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     /** Inserts an image (already-read bytes) after the given block (B14). */     fun insertImage(blockIndex: Int, fileName: String, bytes: ByteArray) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.TextDocument ?: return-        val safeName = fileName.substringAfterLast('/').ifBlank { "image" }-        val path = "Pictures/$safeName"+        val path = uniqueImagePath(doc.images.keys, fileName)         val content = doc.content.toMutableList()         val at = (blockIndex + 1).coerceIn(0, content.size)         content.add(at, OdfContentBlock.Image(OdfImage(path = path, imageData = bytes)))         updateDocument(doc.copy(content = content, images = doc.images + (path to bytes)))     } +    /** Generates a unique package path for a newly-inserted image so two inserts never collide. (A6) */+    private fun uniqueImagePath(existing: Set<String>, fileName: String): String {+        val safe = fileName.substringAfterLast('/').ifBlank { "image" }+        val base = safe.substringBeforeLast('.', safe)+        val ext = safe.substringAfterLast('.', "")+        var candidate = "Pictures/$safe"+        var n = 1+        while (candidate in existing) {+            candidate = if (ext.isNotEmpty()) "Pictures/${base}_$n.$ext" else "Pictures/${base}_$n"+            n+++        }+        return candidate+    }+     /** Sets non-destructive crop insets on a text-document image block. (Phase 5) */     fun setImageCrop(blockIndex: Int, left: Float, top: Float, right: Float, bottom: Float) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.TextDocument ?: return@@ -986,10 +1006,11 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun updateCellText(sheetIndex: Int, rowIndex: Int, cellIndex: Int, newText: String) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val rows = sheet.rows.toMutableList()-        val row = rows[rowIndex]+        val row = rows.getOrNull(rowIndex) ?: return         val cells = row.cells.toMutableList()+        if (cellIndex !in cells.indices) return         cells[cellIndex] = if (newText.startsWith("=")) {             // Typed formula (H49): store as OpenFormula, drop cached numeric value.             cells[cellIndex].copy(text = newText, formula = newText, valueType = "float", numberValue = null)@@ -1006,7 +1027,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun addRow(sheetIndex: Int, afterRowIndex: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val rows = sheet.rows.toMutableList()         val colCount = rows.getOrNull(afterRowIndex)?.cells?.size ?: 1         rows.add(afterRowIndex + 1, OdfRow(List(colCount) { OdfCell(text = "") }))@@ -1017,7 +1038,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun addColumn(sheetIndex: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val rows = sheet.rows.map { row -> OdfRow(row.cells + OdfCell(text = "")) }         sheets[sheetIndex] = sheet.copy(rows = rows)         updateDocument(doc.copy(sheets = sheets))@@ -1026,8 +1047,8 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun deleteRow(sheetIndex: Int, rowIndex: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]-        if (sheet.rows.size <= 1) return+        val sheet = sheets.getOrNull(sheetIndex) ?: return+        if (sheet.rows.size <= 1 || rowIndex !in sheet.rows.indices) return         val rows = sheet.rows.toMutableList()         rows.removeAt(rowIndex)         sheets[sheetIndex] = sheet.copy(rows = rows)@@ -1037,7 +1058,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun deleteColumn(sheetIndex: Int, colIndex: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val rows = sheet.rows.map { row ->             val cells = row.cells.toMutableList()             if (colIndex < cells.size && cells.size > 1) cells.removeAt(colIndex)@@ -1050,7 +1071,8 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun renameSheet(sheetIndex: Int, newName: String) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        sheets[sheetIndex] = sheets[sheetIndex].copy(name = newName)+        val sheet = sheets.getOrNull(sheetIndex) ?: return+        sheets[sheetIndex] = sheet.copy(name = newName)         updateDocument(doc.copy(sheets = sheets))     } @@ -1064,7 +1086,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)      fun deleteSheet(sheetIndex: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return-        if (doc.sheets.size <= 1) return+        if (doc.sheets.size <= 1 || sheetIndex !in doc.sheets.indices) return         val sheets = doc.sheets.toMutableList()         sheets.removeAt(sheetIndex)         updateDocument(doc.copy(sheets = sheets))@@ -1095,10 +1117,61 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         modifyCell(doc, sheetIndex, rowIndex, cellIndex) { it.copy(alignment = alignment) }     } +    /** Sets a cell border color. (C2) */+    fun setCellBorder(sheetIndex: Int, rowIndex: Int, cellIndex: Int, color: Long?) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return+        modifyCell(doc, sheetIndex, rowIndex, cellIndex) { it.copy(borderColor = color) }+    }++    /** Sets a cell's number/date/currency/percentage display format. (C2/B6) */+    fun setCellNumberFormat(sheetIndex: Int, rowIndex: Int, cellIndex: Int, format: OdfNumberFormat?) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return+        modifyCell(doc, sheetIndex, rowIndex, cellIndex) {+            it.copy(numberFormat = format, valueType = when {+                format == null -> it.valueType+                format.isDate -> "date"+                format.percent -> "percentage"+                format.currencySymbol != null -> "currency"+                else -> "float"+            })+        }+    }++    /** Fills the source cell down to the last row of the sheet. (C2) */+    fun fillDownToEnd(sheetIndex: Int, srcRow: Int, col: Int) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return+        val last = doc.sheets.getOrNull(sheetIndex)?.rows?.lastIndex ?: return+        fillDown(sheetIndex, srcRow, col, last)+    }++    /** Copies the source cell's value/formula/format down to the rows below it in the same column. (C2) */+    fun fillDown(sheetIndex: Int, srcRow: Int, col: Int, toRow: Int) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return+        val sheets = doc.sheets.toMutableList()+        val sheet = sheets.getOrNull(sheetIndex) ?: return+        val src = sheet.rows.getOrNull(srcRow)?.cells?.getOrNull(col) ?: return+        if (toRow <= srcRow) return+        val rows = sheet.rows.toMutableList()+        for (r in (srcRow + 1)..toRow) {+            val row = rows.getOrNull(r) ?: continue+            if (col !in row.cells.indices) continue+            val cells = row.cells.toMutableList()+            cells[col] = cells[col].copy(+                text = src.text, formula = src.formula, valueType = src.valueType,+                numberValue = src.numberValue, numberFormat = src.numberFormat,+                bold = src.bold, italic = src.italic, textColor = src.textColor,+                backgroundColor = src.backgroundColor, alignment = src.alignment+            )+            rows[r] = OdfRow(cells)+        }+        sheets[sheetIndex] = sheet.copy(rows = rows)+        updateDocument(doc.copy(sheets = sheets))+    }+     fun mergeCells(sheetIndex: Int, startRow: Int, startCol: Int, endRow: Int, endCol: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val rows = sheet.rows.toMutableList()         val colSpan = endCol - startCol + 1         val rowSpan = endRow - startRow + 1@@ -1140,7 +1213,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)     fun sortRows(sheetIndex: Int, colIndex: Int, ascending: Boolean) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val sorted = sheet.rows.sortedWith(compareBy<OdfRow> {             val text = it.cells.getOrNull(colIndex)?.text ?: ""             text.toDoubleOrNull() ?: Double.MAX_VALUE@@ -1151,9 +1224,11 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)      private fun modifyCell(doc: OdfDocument.Spreadsheet, sheetIndex: Int, rowIndex: Int, cellIndex: Int, transform: (OdfCell) -> OdfCell) {         val sheets = doc.sheets.toMutableList()-        val sheet = sheets[sheetIndex]+        val sheet = sheets.getOrNull(sheetIndex) ?: return         val rows = sheet.rows.toMutableList()-        val cells = rows[rowIndex].cells.toMutableList()+        val row = rows.getOrNull(rowIndex) ?: return+        val cells = row.cells.toMutableList()+        if (cellIndex !in cells.indices) return         cells[cellIndex] = transform(cells[cellIndex])         rows[rowIndex] = OdfRow(cells)         sheets[sheetIndex] = sheet.copy(rows = rows)@@ -1270,8 +1345,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return         val slides = doc.slides.toMutableList()         val slide = slides.getOrNull(slideIndex) ?: return-        val safeName = fileName.substringAfterLast('/').ifBlank { "image" }-        val path = "Pictures/$safeName"+        val path = uniqueImagePath(doc.images.keys, fileName)         val frame = OdfFrame(x = 300f, y = 200f, width = 400f, height = 300f, paragraphs = emptyList(),             image = OdfImage(path = path, imageData = bytes))         slides[slideIndex] = slide.copy(elements = slide.elements + OdfSlideElement.Frame(frame))@@ -1312,8 +1386,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return         val sheets = doc.sheets.toMutableList()         val sheet = sheets.getOrNull(sheetIndex) ?: return-        val safeName = fileName.substringAfterLast('/').ifBlank { "image" }-        val path = "Pictures/$safeName"+        val path = uniqueImagePath(doc.images.keys, fileName)         val frame = OdfFrame(x = 100f, y = 100f, width = 320f, height = 240f, paragraphs = emptyList(),             image = OdfImage(path = path, imageData = bytes))         sheets[sheetIndex] = sheet.copy(floating = sheet.floating + OdfSlideElement.Frame(frame))@@ -1444,6 +1517,46 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         updateDocument(doc.copy(slides = slides))     } +    /** Duplicates a slide element, offset slightly so it's visible. (C1) */+    fun duplicateSlideElement(slideIndex: Int, elementIndex: Int) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return+        val slides = doc.slides.toMutableList()+        val slide = slides.getOrNull(slideIndex) ?: return+        val el = slide.elements.getOrNull(elementIndex) ?: return+        val b = el.bounds()+        val copy = setElementBounds(el, b[0] + 20f, b[1] + 20f, b[2], b[3])+        val elements = slide.elements.toMutableList()+        elements.add(elementIndex + 1, copy)+        slides[slideIndex] = slide.copy(elements = elements)+        updateDocument(doc.copy(slides = slides))+    }++    /** Reorders a slide element in document order (= ODF render z-order). delta<0 = back, delta>0 = front. (C1) */+    fun reorderSlideElement(slideIndex: Int, elementIndex: Int, toFront: Boolean) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return+        val slides = doc.slides.toMutableList()+        val slide = slides.getOrNull(slideIndex) ?: return+        if (elementIndex !in slide.elements.indices) return+        val elements = slide.elements.toMutableList()+        val item = elements.removeAt(elementIndex)+        if (toFront) elements.add(item) else elements.add(0, item)+        slides[slideIndex] = slide.copy(elements = elements)+        updateDocument(doc.copy(slides = slides))+    }++    /** Rotates an image element on a slide by the given delta degrees. (C4) */+    fun rotateSlideImage(slideIndex: Int, elementIndex: Int, deltaDegrees: Float) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return+        val slides = doc.slides.toMutableList()+        val slide = slides.getOrNull(slideIndex) ?: return+        val el = slide.elements.getOrNull(elementIndex) as? OdfSlideElement.Frame ?: return+        val img = el.frame.image ?: return+        val elements = slide.elements.toMutableList()+        elements[elementIndex] = OdfSlideElement.Frame(el.frame.copy(image = img.copy(rotationDegrees = (img.rotationDegrees + deltaDegrees) % 360f)))+        slides[slideIndex] = slide.copy(elements = elements)+        updateDocument(doc.copy(slides = slides))+    }+     /** Sets crop insets on an image frame element of a slide. (Phase 5) */     fun setSlideImageCrop(slideIndex: Int, elementIndex: Int, left: Float, top: Float, right: Float, bottom: Float) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return