Modern Apps git

← Modern-Apps.git

office: UI consistency

Commit
00cc27bb69dc9ee32fdfa3f28162045ef531de0a
Author
Vayun Mathur <[email protected]>
When
2026-06-21 00:41 UTC (5 months ago)
Parents
cd12394

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 937fd84c19..a9f0648c24 100644--- a/office/src/main/java/com/vayunmathur/office/MainActivity.kt+++ b/office/src/main/java/com/vayunmathur/office/MainActivity.kt@@ -214,6 +214,16 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:     var fileMenu by remember { mutableStateOf(false) }     var insertMenu by remember { mutableStateOf(false) }     var viewMenu by remember { mutableStateOf(false) }+    // Hoisted selection for the shared bottom bar (Phase 2).+    var activeCell by remember { mutableStateOf<Triple<Int, Int, Int>?>(null) }+    var activeSlide by remember { mutableIntStateOf(0) }+    var activeSlideEl by remember { mutableIntStateOf(-1) }+    var showCellTextColor by remember { mutableStateOf(false) }+    var showCellBgColor by remember { mutableStateOf(false) }+    var showSlideTextColor by remember { mutableStateOf(false) }+    var chartForSlide by remember { mutableStateOf(false) }+    var chartForSheet by remember { mutableStateOf(false) }+    var cropImageBlock by remember { mutableIntStateOf(-1) }      val isEditMode by viewModel.isEditMode.collectAsState()     val hasUnsavedChanges by viewModel.hasUnsavedChanges.collectAsState()@@ -251,7 +261,12 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:             try {                 val bytes = context.contentResolver.openInputStream(it)?.use { s -> s.readBytes() } ?: return@let                 val name = it.lastPathSegment?.substringAfterLast('/') ?: "image.png"-                viewModel.insertImage(maxOf(0, focusedPara), name, bytes)+                when (document) {+                    is OdfDocument.TextDocument -> viewModel.insertImage(maxOf(0, focusedPara), name, bytes)+                    is OdfDocument.Presentation -> viewModel.insertImageIntoSlide(activeSlide, name, bytes)+                    is OdfDocument.Spreadsheet -> viewModel.insertImageIntoSheet(activeCell?.first ?: 0, name, bytes)+                    else -> {}+                }             } catch (_: Exception) {}         }     }@@ -429,7 +444,39 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                 }             },             bottomBar = {-                if (isTextDoc) QuickFormatBar(document = document, runStart = activeRunStart, runEnd = activeRunEnd, selStart = selStart, selEnd = selEnd, activeTableBlock = activeTableBlock, activeTableRow = activeTableRow, activeTableCol = activeTableCol, viewModel = viewModel, onColorClick = { showColorPicker = true }, onInsertTable = { showInsertTable = true }, onFontSize = { showFontSizePicker = true })+                if (canEdit) {+                    val formatTarget: FormatTarget = when {+                        isTextDoc && activeRunStart >= 0 -> FormatTarget.TextRun(activeRunStart, activeRunEnd, selStart, selEnd)+                        isSpreadsheet && (activeCell?.second ?: -1) >= 0 -> FormatTarget.Cell(activeCell!!.first, activeCell!!.second, activeCell!!.third)+                        isPresentation && activeSlideEl >= 0 -> FormatTarget.Element(activeSlide, activeSlideEl)+                        else -> FormatTarget.None+                    }+                    val caps = when {+                        isTextDoc -> DocCaps(insertImage = true, insertChart = true, insertTable = true)+                        isPresentation -> DocCaps(insertImage = true, insertShape = true, insertChart = true)+                        isSpreadsheet -> DocCaps(insertImage = true, insertShape = true, insertChart = true)+                        else -> DocCaps()+                    }+                    val activeSheet = activeCell?.first ?: 0+                    val actions = BottomBarActions(+                        onTextColor = { showColorPicker = true },+                        onCellTextColor = { showCellTextColor = true },+                        onCellBgColor = { showCellBgColor = true },+                        onSlideTextColor = { showSlideTextColor = true },+                        onFontSize = { showFontSizePicker = true },+                        onInsertImage = { imagePickerLauncher.launch("image/*") },+                        onInsertShape = { kind ->+                            when {+                                isPresentation -> viewModel.addShapeToSlide(activeSlide, kind.name.lowercase())+                                isSpreadsheet -> viewModel.addShapeToSheet(activeSheet, kind.name.lowercase())+                            }+                        },+                        onInsertChart = { editingChartBlock = -1; chartForSlide = isPresentation; chartForSheet = isSpreadsheet; showChartEditor = true },+                        onInsertTable = { showInsertTable = true },+                        onDeleteElement = { if (activeSlideEl >= 0) { viewModel.deleteSlideElement(activeSlide, activeSlideEl); activeSlideEl = -1 } }+                    )+                    OfficeBottomBar(document, formatTarget, caps, viewModel, actions, activeTableBlock, activeTableRow, activeTableCol)+                }             }         ) { paddingValues ->             Box(Modifier.padding(paddingValues)) {@@ -439,7 +486,8 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                         onRunTextChange = { rs, re, text -> viewModel.updateParagraphRun(rs, re, text) },                         onCellTextChange = { bi, r, c, text -> viewModel.updateTextTableCell(bi, r, c, text) },                         onCellFocus = { bi, r, c -> activeTableBlock = bi; activeTableRow = r; activeTableCol = c },-                        onChartClick = { bi -> editingChartBlock = bi; showChartEditor = true })+                        onChartClick = { bi -> editingChartBlock = bi; showChartEditor = true },+                        onCropImage = { bi -> cropImageBlock = bi })                     is OdfDocument.Spreadsheet -> SpreadsheetView(doc = document, searchQuery = searchQuery, fontSizeMultiplier = fontSizeMultiplier, isEditMode = isEditMode,                         onCellTextChange = { s, r, c, t -> viewModel.updateCellText(s, r, c, t) }, onAddRow = { s, r -> viewModel.addRow(s, r) }, onAddColumn = { s -> viewModel.addColumn(s) },                         onDeleteRow = { s, r -> viewModel.deleteRow(s, r) }, onDeleteColumn = { s, c -> viewModel.deleteColumn(s, c) },@@ -448,14 +496,20 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                         onCellColor = { s, r, c, clr -> viewModel.setCellColor(s, r, c, clr) }, onCellBgColor = { s, r, c, clr -> viewModel.setCellBgColor(s, r, c, clr) },                         onCellAlignment = { s, r, c, a -> viewModel.setCellAlignment(s, r, c, a) },                         onMergeCells = { s, sr, sc, er, ec -> viewModel.mergeCells(s, sr, sc, er, ec) }, onUnmergeCells = { s, r, c -> viewModel.unmergeCells(s, r, c) },-                        onSort = { s, col, asc -> viewModel.sortRows(s, col, asc) })+                        onSort = { s, col, asc -> viewModel.sortRows(s, col, asc) },+                        onCellSelected = { s, r, c -> activeCell = Triple(s, r, c) },+                        onFloatingBoundsChange = { s, e, x, y, w, h -> viewModel.setSheetElementBounds(s, e, x, y, w, h) },+                        onFloatingTextChange = { s, e, t -> viewModel.updateSheetElementText(s, e, t) },+                        onFloatingDelete = { s, e -> viewModel.deleteSheetElement(s, e) })                     is OdfDocument.Presentation -> PresentationView(doc = document, isEditMode = isEditMode,                         onAddSlide = { viewModel.addSlide(it) }, onDeleteSlide = { viewModel.deleteSlide(it) },                         onDuplicateSlide = { viewModel.duplicateSlide(it) }, onMoveSlideUp = { viewModel.moveSlideUp(it) }, onMoveSlideDown = { viewModel.moveSlideDown(it) },                         onElementTextChange = { s, e, t -> viewModel.updateSlideElementText(s, e, t) }, onAddTextBox = { viewModel.addTextBoxToSlide(it) },-                        onElementBold = { s, e -> viewModel.toggleSlideElementBold(s, e) }, onElementItalic = { s, e -> viewModel.toggleSlideElementItalic(s, e) },-                        onElementUnderline = { s, e -> viewModel.toggleSlideElementUnderline(s, e) }, onElementColor = { s, e, c -> viewModel.setSlideElementColor(s, e, c) },-                        onElementAlign = { s, e, a -> viewModel.setSlideElementAlignment(s, e, a) })+                        onElementBoundsChange = { s, e, x, y, w, h -> viewModel.setSlideElementBounds(s, e, x, y, w, h) },+                        onDeleteElement = { s, e -> viewModel.deleteSlideElement(s, e) },+                        selectedElement = activeSlideEl,+                        onSlideChange = { activeSlide = it },+                        onElementSelected = { s, e -> activeSlide = s; activeSlideEl = e })                     is OdfDocument.Drawing -> DrawingView(document)                 }             }@@ -488,123 +542,36 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:             onDismiss = { showHeaderFooter = false }         )     }-    if (showChartEditor) {-        val existing = if (editingChartBlock >= 0) ((document as? OdfDocument.TextDocument)?.content?.getOrNull(editingChartBlock) as? OdfContentBlock.Chart)?.chart else null-        ChartEditorDialog(-            initial = existing,-            onConfirm = { ch -> if (editingChartBlock >= 0) viewModel.updateChart(editingChartBlock, ch) else viewModel.insertChart(maxOf(0, focusedPara), ch) },-            onDismiss = { showChartEditor = false; editingChartBlock = -1 }-        )+    if (showCellTextColor && (activeCell?.second ?: -1) >= 0) {+        val (s, r, c) = activeCell!!+        ColorPickerDialog("Text Color", onColorSelected = { viewModel.setCellColor(s, r, c, it) }, onDismiss = { showCellTextColor = false })     }-}--@Composable-private fun QuickFormatBar(document: OdfDocument, runStart: Int, runEnd: Int, selStart: Int, selEnd: Int, activeTableBlock: Int, activeTableRow: Int, activeTableCol: Int, viewModel: OfficeViewModel, onColorClick: () -> Unit, onInsertTable: () -> Unit, onFontSize: () -> Unit = {}) {-    val doc = document as? OdfDocument.TextDocument ?: return-    val enabled = runStart >= 0-    val focusedPara = if (enabled) viewModel.runParagraphIndexAt(runStart, runEnd, selStart) else -1-    val para = (doc.content.getOrNull(focusedPara) as? OdfContentBlock.Paragraph)?.paragraph-    var styleMenu by remember { mutableStateOf(false) }-    var alignMenu by remember { mutableStateOf(false) }-    var tableMenu by remember { mutableStateOf(false) }--    val isBold = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.bold }-    val isItalic = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.italic }-    val isUnderline = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.underline }-    val isStrike = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.strikethrough }-    val isBullet = para?.style == ParagraphStyle.LIST_ITEM && para.listType == ListType.BULLET-    val isNumbered = para?.style == ParagraphStyle.LIST_ITEM && para.listType == ListType.NUMBERED--    val styleLabel = when (para?.style) {-        ParagraphStyle.HEADING1 -> "H1"; ParagraphStyle.HEADING2 -> "H2"; ParagraphStyle.HEADING3 -> "H3"; ParagraphStyle.HEADING4 -> "H4"; else -> "Normal"+    if (showCellBgColor && (activeCell?.second ?: -1) >= 0) {+        val (s, r, c) = activeCell!!+        ColorPickerDialog("Background Color", onColorSelected = { viewModel.setCellBgColor(s, r, c, it) }, onDismiss = { showCellBgColor = false })     }-    val alignIcon = when (para?.alignment) {-        TextAlign.Center -> R.drawable.format_align_center_24px-        TextAlign.End, TextAlign.Right -> R.drawable.format_align_right_24px-        TextAlign.Justify -> R.drawable.format_align_justify_24px-        else -> R.drawable.format_align_left_24px+    if (showSlideTextColor && activeSlideEl >= 0) {+        ColorPickerDialog("Text Color", onColorSelected = { viewModel.setSlideElementColor(activeSlide, activeSlideEl, it) }, onDismiss = { showSlideTextColor = false })     }-    fun setStyle(s: ParagraphStyle) { viewModel.mutateRunParagraphs(runStart, runEnd, selStart, selEnd) { it.copy(style = s) } }-    fun setAlign(a: TextAlign) { viewModel.mutateRunParagraphs(runStart, runEnd, selStart, selEnd) { it.copy(alignment = a) } }--    Surface(tonalElevation = 3.dp) {-        Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).navigationBarsPadding().imePadding().padding(horizontal = 4.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {-            Box {-                TextButton(onClick = { styleMenu = true }, enabled = enabled) {-                    Text(styleLabel)-                    Icon(painterResource(R.drawable.arrow_drop_down_24px), contentDescription = "Paragraph style")-                }-                DropdownMenu(expanded = styleMenu, onDismissRequest = { styleMenu = false }) {-                    DropdownMenuItem(text = { Text("Normal") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.BODY) })-                    DropdownMenuItem(text = { Text("Heading 1") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING1) })-                    DropdownMenuItem(text = { Text("Heading 2") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING2) })-                    DropdownMenuItem(text = { Text("Heading 3") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING3) })-                    DropdownMenuItem(text = { Text("Heading 4") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING4) })-                }-            }-            FmtIcon(R.drawable.format_bold_24px, isBold, enabled, "Bold") { val t = !isBold; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(bold = t) } }-            FmtIcon(R.drawable.format_italic_24px, isItalic, enabled, "Italic") { val t = !isItalic; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(italic = t) } }-            FmtIcon(R.drawable.format_underlined_24px, isUnderline, enabled, "Underline") { val t = !isUnderline; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(underline = t) } }-            FmtIcon(R.drawable.format_strikethrough_24px, isStrike, enabled, "Strikethrough") { val t = !isStrike; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(strikethrough = t) } }-            FmtIcon(R.drawable.format_color_text_24px, false, enabled, "Text color") { onColorClick() }-            Box {-                FmtIcon(alignIcon, false, enabled, "Alignment") { alignMenu = true }-                DropdownMenu(expanded = alignMenu, onDismissRequest = { alignMenu = false }) {-                    DropdownMenuItem(text = { Text("Left") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_left_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.Start) })-                    DropdownMenuItem(text = { Text("Center") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_center_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.Center) })-                    DropdownMenuItem(text = { Text("Right") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_right_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.End) })-                    DropdownMenuItem(text = { Text("Justify") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_justify_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.Justify) })-                }-            }-            FmtIcon(R.drawable.format_list_bulleted_24px, isBullet, enabled, "Bulleted list") { if (focusedPara >= 0) viewModel.toggleListItem(focusedPara) }-            FmtIcon(R.drawable.format_list_numbered_24px, isNumbered, enabled, "Numbered list") { if (focusedPara >= 0) viewModel.toggleNumberedList(focusedPara) }-            FmtIcon(R.drawable.format_indent_increase_24px, false, enabled, "Increase indent") { if (focusedPara >= 0) viewModel.indentParagraph(focusedPara) }-            FmtIcon(R.drawable.format_indent_decrease_24px, false, enabled, "Decrease indent") { if (focusedPara >= 0) viewModel.outdentParagraph(focusedPara) }-            Box {-                val tableEnabled = activeTableBlock >= 0-                TextButton(onClick = { tableMenu = true }) {-                    Text("Table")-                    Icon(painterResource(R.drawable.arrow_drop_down_24px), contentDescription = "Table options")-                }-                DropdownMenu(expanded = tableMenu, onDismissRequest = { tableMenu = false }) {-                    DropdownMenuItem(text = { Text("Insert table") }, onClick = { tableMenu = false; onInsertTable() })-                    HorizontalDivider()-                    DropdownMenuItem(text = { Text("Insert row below") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableAddRow(activeTableBlock, activeTableRow) })-                    DropdownMenuItem(text = { Text("Insert column right") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableAddColumn(activeTableBlock, activeTableCol) })-                    DropdownMenuItem(text = { Text("Delete row") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableDeleteRow(activeTableBlock, activeTableRow) })-                    DropdownMenuItem(text = { Text("Delete column") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableDeleteColumn(activeTableBlock, activeTableCol) })-                    HorizontalDivider()-                    DropdownMenuItem(text = { Text("Bold cell") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.setTextTableCellSpanFormat(activeTableBlock, activeTableRow, activeTableCol) { it.copy(bold = !it.bold) } })-                    DropdownMenuItem(text = { Text("Italic cell") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.setTextTableCellSpanFormat(activeTableBlock, activeTableRow, activeTableCol) { it.copy(italic = !it.italic) } })-                    DropdownMenuItem(text = { Text("Merge with right") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.mergeTextTableCells(activeTableBlock, activeTableRow, activeTableCol, activeTableRow, activeTableCol + 1) })-                    DropdownMenuItem(text = { Text("Merge with below") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.mergeTextTableCells(activeTableBlock, activeTableRow, activeTableCol, activeTableRow + 1, activeTableCol) })-                    DropdownMenuItem(text = { Text("Unmerge cell") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.unmergeTextTableCells(activeTableBlock, activeTableRow, activeTableCol) })-                }-            }-            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("Font size…") }, onClick = { moreMenu = false; onFontSize() })-                    DropdownMenuItem(text = { Text("Clear formatting") }, onClick = { moreMenu = false; viewModel.clearRunFormatting(runStart, runEnd, selStart, selEnd) })-                    HorizontalDivider()-                    DropdownMenuItem(text = { Text("Demote list item") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; if (focusedPara >= 0) viewModel.changeListLevel(focusedPara, 1) })-                    DropdownMenuItem(text = { Text("Promote list item") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; if (focusedPara >= 0) viewModel.changeListLevel(focusedPara, -1) })-                    DropdownMenuItem(text = { Text("Restart numbering") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; if (focusedPara >= 0) viewModel.restartNumbering(focusedPara) })-                    HorizontalDivider()-                    DropdownMenuItem(text = { Text("Duplicate paragraph") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; viewModel.duplicateParagraph(focusedPara) })-                    DropdownMenuItem(text = { Text("Move paragraph up") }, enabled = focusedPara > 0, onClick = { moreMenu = false; viewModel.moveParagraphUp(focusedPara) })-                    DropdownMenuItem(text = { Text("Move paragraph down") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; viewModel.moveParagraphDown(focusedPara) })-                    DropdownMenuItem(text = { Text("Delete paragraph", color = MaterialTheme.colorScheme.error) }, enabled = focusedPara >= 0, onClick = { moreMenu = false; viewModel.deleteParagraph(focusedPara) })-                }-            }-        }+    if (cropImageBlock >= 0) {+        val img = ((document as? OdfDocument.TextDocument)?.content?.getOrNull(cropImageBlock) as? OdfContentBlock.Image)?.image+        if (img != null) ImageCropDialog(image = img, onApply = { l, t, r, b -> viewModel.setImageCrop(cropImageBlock, l, t, r, b) }, onDismiss = { cropImageBlock = -1 })+        else cropImageBlock = -1     }-}--@Composable private fun FmtIcon(res: Int, active: Boolean, enabled: Boolean, desc: String, onClick: () -> Unit) {-    IconButton(onClick = onClick, enabled = enabled, modifier = Modifier.size(40.dp)) {-        Icon(painterResource(res), contentDescription = desc, tint = if (active && enabled) MaterialTheme.colorScheme.primary else LocalContentColor.current)+    if (showChartEditor) {+        val existing = if (!chartForSlide && editingChartBlock >= 0) ((document as? OdfDocument.TextDocument)?.content?.getOrNull(editingChartBlock) as? OdfContentBlock.Chart)?.chart else null+        ChartEditorDialog(+            initial = existing,+            onConfirm = { ch ->+                when {+                    chartForSlide -> viewModel.insertChartIntoSlide(activeSlide, ch)+                    chartForSheet -> viewModel.insertChartIntoSheet(activeCell?.first ?: 0, ch)+                    editingChartBlock >= 0 -> viewModel.updateChart(editingChartBlock, ch)+                    else -> viewModel.insertChart(maxOf(0, focusedPara), ch)+                }+            },+            onDismiss = { showChartEditor = false; editingChartBlock = -1; chartForSlide = false; chartForSheet = 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 ab32b2dccd..2531423ca0 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt@@ -151,7 +151,12 @@ data class OdfImage(     val height: Float = 0f,     val anchorType: String = "",     // Rotation in degrees clockwise (E38).-    val rotationDegrees: Float = 0f+    val rotationDegrees: Float = 0f,+    // Non-destructive crop insets as fractions of the source image [0,1). (Phase 5)+    val cropLeftPct: Float = 0f,+    val cropTopPct: Float = 0f,+    val cropRightPct: Float = 0f,+    val cropBottomPct: Float = 0f )  data class OdfTable(@@ -176,7 +181,8 @@ data class OdfTableCell( data class OdfSheet(     val name: String,     val rows: List<OdfRow>,-    val columnWidths: List<Float?> = emptyList()+    val columnWidths: List<Float?> = emptyList(),+    val floating: List<OdfSlideElement> = emptyList() )  data class OdfRow(val cells: List<OdfCell>)@@ -226,6 +232,23 @@ sealed class OdfSlideElement {     data class Shape(val shape: OdfShape) : OdfSlideElement() } +/** Geometry (x, y, width, height) of a floating element, in px@96. (Phase 1) */+fun OdfSlideElement.bounds(): FloatArray = when (this) {+    is OdfSlideElement.Frame -> floatArrayOf(frame.x, frame.y, frame.width, frame.height)+    is OdfSlideElement.Shape -> floatArrayOf(shape.x, shape.y, shape.width, shape.height)+}++/** Returns a copy of the element repositioned/resized to the given bounds (px@96). (Phase 1) */+fun setElementBounds(el: OdfSlideElement, x: Float, y: Float, w: Float, h: Float): OdfSlideElement = when (el) {+    is OdfSlideElement.Frame -> OdfSlideElement.Frame(el.frame.copy(x = x, y = y, width = w, height = h))+    is OdfSlideElement.Shape -> OdfSlideElement.Shape(when (val s = el.shape) {+        is OdfShape.Rect -> s.copy(x = x, y = y, width = w, height = h)+        is OdfShape.Ellipse -> s.copy(x = x, y = y, width = w, height = h)+        is OdfShape.Line -> s.copy(x = x, y = y, width = w, height = h)+        is OdfShape.CustomShape -> s.copy(x = x, y = y, width = w, height = h)+    })+}+ data class OdfFrame(     val x: Float,     val y: Float,@@ -233,6 +256,7 @@ data class OdfFrame(     val height: Float,     val paragraphs: List<OdfParagraph>,     val image: OdfImage? = null,+    val chart: OdfChart? = null,     val fillColor: Long? = null,     val strokeColor: Long? = null,     val strokeWidth: Float? = null
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 39e49c00b2..cc0f808428 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt@@ -154,13 +154,31 @@ object OdfParser {     }      private fun parseColor(hex: String): Long? {-        if (!hex.startsWith("#")) return null         return try {             val colorStr = hex.removePrefix("#")             0xFF000000L or colorStr.toLong(16)         } catch (_: Exception) { null }     } +    /** Parses an fo:clip="rect(top right bottom left)" value (percent tokens) into [left, top, right, bottom] fractions. (Phase 5) */+    private fun parseClip(value: String?): FloatArray? {+        if (value == null) 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+        fun f(s: String): Float {+            val t = s.trim()+            return when {+                t.endsWith("%") -> (t.dropLast(1).toFloatOrNull() ?: 0f) / 100f+                else -> 0f+            }.coerceIn(0f, 0.95f)+        }+        val top = f(parts[0]); val right = f(parts[1]); val bottom = f(parts[2]); val left = f(parts[3])+        if (top == 0f && right == 0f && bottom == 0f && left == 0f) return null+        return floatArrayOf(left, top, right, bottom)+    }+     /** Converts an ODF draw:transform rotate(theta) into degrees clockwise for Compose (E38). */     private fun parseRotationDegrees(transform: String?): Float {         if (transform == null) return 0f@@ -591,6 +609,7 @@ object OdfParser {         var currentHref: String? = null         var pendingFrameW = 0f         var pendingFrameH = 0f+        var pendingFrameClip: String? = null          while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth && parser.name == endTag)) {             when (eventType) {@@ -615,13 +634,17 @@ object OdfParser {                     "frame" -> {                         pendingFrameW = parseDimension(getAttr(parser, "width"))                         pendingFrameH = parseDimension(getAttr(parser, "height"))+                        pendingFrameClip = getAttr(parser, "clip")                     }                     "image" -> {                         val href = getAttr(parser, "href")                         val w = pendingFrameW                         val h = pendingFrameH+                        val clip = parseClip(pendingFrameClip)                         if (href != null && images.containsKey(href)) {-                            imagesOut?.add(OdfImage(path = href, imageData = images[href]!!, width = w, height = h))+                            var img = OdfImage(path = href, imageData = images[href]!!, width = w, height = h)+                            if (clip != null) img = img.copy(cropLeftPct = clip[0], cropTopPct = clip[1], cropRightPct = clip[2], cropBottomPct = clip[3])+                            imagesOut?.add(img)                             skipElement(parser)                         } else {                             // Look for inline base64 binary-data. (A2/E37)@@ -633,7 +656,9 @@ object OdfParser {                                     if (imgEvent == XmlPullParser.TEXT) {                                         try {                                             val bytes = Base64.decode(parser.text.trim(), Base64.DEFAULT)-                                            imagesOut?.add(OdfImage(path = "inline", imageData = bytes, width = w, height = h))+                                            var img = OdfImage(path = "inline", imageData = bytes, width = w, height = h)+                                            if (clip != null) img = img.copy(cropLeftPct = clip[0], cropTopPct = clip[1], cropRightPct = clip[2], cropBottomPct = clip[3])+                                            imagesOut?.add(img)                                         } catch (_: Exception) {}                                     }                                 }@@ -1112,34 +1137,41 @@ 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)-                sheets.add(OdfSheet(name, result.first, result.second))+                val result = parseSheetContent(parser, styles, numberStyles, images)+                sheets.add(OdfSheet(name, result.first, result.second, result.third))             }             eventType = parser.next()         }         return OdfDocument.Spreadsheet(title, sheets, metadata, images)     } -    private fun parseSheetContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>): Pair<List<OdfRow>, List<Float?>> {+    private fun parseSheetContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>, images: Map<String, ByteArray>): Triple<List<OdfRow>, List<Float?>, List<OdfSlideElement>> {         val rows = mutableListOf<OdfRow>()         val columnWidths = mutableListOf<Float?>()+        val floating = mutableListOf<OdfSlideElement>()         val depth = parser.depth         var eventType = parser.next()          while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth)) {-            if (eventType == XmlPullParser.START_TAG) when (parser.name) {-                "table-column" -> {-                    val repeated = getAttr(parser, "number-columns-repeated")?.toIntOrNull() ?: 1-                    val styleName = getAttr(parser, "style-name")-                    val width = resolveStyle(styleName, styles).columnWidth-                    repeat(repeated.coerceAtMost(200)) { columnWidths.add(width) }-                }-                "table-row" -> {-                    val repeated = getAttr(parser, "number-rows-repeated")?.toIntOrNull() ?: 1-                    val cells = parseSpreadsheetCells(parser, styles, numberStyles)-                    // Preserve row coordinates-                    // references resolve correctly; trailing empties are trimmed afterward. (H49/H51)-                    repeat(repeated.coerceAtMost(1000)) { rows.add(OdfRow(cells)) }+            if (eventType == XmlPullParser.START_TAG) {+                val isDraw = parser.namespace?.contains("draw") == true+                when (parser.name) {+                    "table-column" -> {+                        val repeated = getAttr(parser, "number-columns-repeated")?.toIntOrNull() ?: 1+                        val styleName = getAttr(parser, "style-name")+                        val width = resolveStyle(styleName, styles).columnWidth+                        repeat(repeated.coerceAtMost(200)) { columnWidths.add(width) }+                    }+                    "table-row" -> {+                        val repeated = getAttr(parser, "number-rows-repeated")?.toIntOrNull() ?: 1+                        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)))+                    "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")))+                    "custom-shape" -> if (isDraw) floating.add(OdfSlideElement.Shape(parseShape(parser, styles, "custom-shape")))                 }             }             eventType = parser.next()@@ -1148,7 +1180,7 @@ object OdfParser {         while (rows.isNotEmpty() && rows.last().cells.all { it.text.isEmpty() && it.formula == null }) {             rows.removeAt(rows.size - 1)         }-        return Pair(rows, columnWidths)+        return Triple(rows, columnWidths, floating)     }      private fun parseSpreadsheetCells(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>): List<OdfCell> {@@ -1277,6 +1309,7 @@ object OdfParser {         val w = parseDimension(getAttr(parser, "width"))         val h = parseDimension(getAttr(parser, "height"))         val rot = parseRotationDegrees(getAttr(parser, "transform"))+        val clip = parseClip(getAttr(parser, "clip"))         val styleName = getAttr(parser, "style-name")         val resolved = resolveStyle(styleName, styles) @@ -1327,7 +1360,10 @@ object OdfParser {             }             eventType = parser.next()         }-        return OdfFrame(x, y, w, h, paragraphs, image, resolved.drawFillColor, resolved.drawStrokeColor, resolved.drawStrokeWidth)+        if (clip != null && image != null) {+            image = image.copy(cropLeftPct = clip[0], cropTopPct = clip[1], cropRightPct = clip[2], cropBottomPct = clip[3])+        }+        return OdfFrame(x, y, w, h, paragraphs, image, 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 045385deff..c396753efa 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt@@ -105,6 +105,8 @@ object OdfSerializer {     private fun serializeSpreadsheet(doc: OdfDocument.Spreadsheet): String {         val cellStyles = LinkedHashMap<String, CellStyleDef>()         val colStyles = LinkedHashMap<String, Float>()+        val spanStyles = mutableMapOf<String, SpanStyleDef>()+        val paraStyles = mutableMapOf<String, ParaStyleDef>()         val body = StringBuilder()         for (sheet in doc.sheets) {             body.append("""<table:table table:name="${esc(sheet.name)}">""")@@ -143,9 +145,16 @@ object OdfSerializer {                 }                 body.append("</table:table-row>")             }+            // Floating objects anchored to the sheet (Phase 4).+            for (element in sheet.floating) {+                when (element) {+                    is OdfSlideElement.Frame -> serializeFrame(body, element.frame, spanStyles, paraStyles)+                    is OdfSlideElement.Shape -> serializeShape(body, element.shape, spanStyles, paraStyles)+                }+            }             body.append("</table:table>")         }-        return buildDocument("office:spreadsheet", mutableMapOf(), mutableMapOf(), cellStyles, colStyles, body.toString())+        return buildDocument("office:spreadsheet", spanStyles, paraStyles, cellStyles, colStyles, body.toString())     }      private fun serializePresentation(doc: OdfDocument.Presentation): String {@@ -236,10 +245,24 @@ object OdfSerializer {         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"/>""")         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)})"""")+        }+    }++    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()+    }+     private fun serializeFrame(         sb: StringBuilder, frame: OdfFrame,         styles: MutableMap<String, SpanStyleDef>,@@ -248,10 +271,17 @@ object OdfSerializer {         sb.append("<draw:frame")         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)         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.paragraphs.isNotEmpty()) {             sb.append("<draw:text-box>")             for (para in frame.paragraphs) serializeParagraph(sb, para, styles, paraStyles, "text:p")
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 e525e5497d..878a8641a9 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt@@ -10,6 +10,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectHorizontalDragGestures+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box@@ -44,6 +46,7 @@ import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.PrimaryScrollableTabRow import androidx.compose.material3.Surface@@ -78,7 +81,9 @@ import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextStyle@@ -97,6 +102,8 @@ import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp@@ -529,7 +536,8 @@ fun TextDocumentView(     onRunTextChange: (Int, Int, String) -> Unit = { _, _, _ -> },     onCellTextChange: (Int, Int, Int, String) -> Unit = { _, _, _, _ -> },     onCellFocus: (Int, Int, Int) -> Unit = { _, _, _ -> },-    onChartClick: (Int) -> Unit = {}+    onChartClick: (Int) -> Unit = {},+    onCropImage: (Int) -> Unit = {} ) {     val segments = remember(doc.content) { buildSegments(doc.content) } @@ -552,7 +560,7 @@ fun TextDocumentView(                     is OdfContentBlock.Table -> TableView(block.table, seg.index, searchQuery, fontSizeMultiplier, onCellTextChange, onCellFocus)                     is OdfContentBlock.Image -> {                         var fullScreen by remember { mutableStateOf(false) }-                        if (fullScreen) FullScreenImage(block.image) { fullScreen = false }+                        if (fullScreen) FullScreenImage(block.image, onCrop = { fullScreen = false; onCropImage(seg.index) }) { fullScreen = false }                         else Box(modifier = Modifier.clickable { fullScreen = true }) { OdfImageView(block.image) }                     }                     is OdfContentBlock.PageBreak -> PageBreakView()@@ -862,10 +870,57 @@ private fun AnnotationPopup(content: String) { }  @Composable-private fun FullScreenImage(image: OdfImage, onDismiss: () -> Unit) {+private fun FullScreenImage(image: OdfImage, onCrop: (() -> Unit)? = null, onDismiss: () -> Unit) {     val bitmap = remember(image.path, image.imageData.size) { BitmapFactory.decodeByteArray(image.imageData, 0, image.imageData.size) }     Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.9f)).clickable { onDismiss() }, contentAlignment = Alignment.Center) {         if (bitmap != null) Image(bitmap = bitmap.asImageBitmap(), contentDescription = null, modifier = Modifier.fillMaxWidth().padding(16.dp), contentScale = ContentScale.Fit)+        if (onCrop != null) {+            TextButton(onClick = onCrop, modifier = Modifier.align(Alignment.TopStart).padding(8.dp)) {+                Icon(painterResource(com.vayunmathur.library.R.drawable.crop_24px), contentDescription = null, tint = Color.White)+                Spacer(Modifier.width(4.dp))+                Text("Crop", color = Color.White)+            }+        }+    }+}++/** Non-destructive crop editor: adjust four insets with a live preview. (Phase 5) */+@Composable+fun ImageCropDialog(image: OdfImage, onApply: (Float, Float, Float, Float) -> Unit, onDismiss: () -> Unit) {+    var left by remember { mutableFloatStateOf(image.cropLeftPct) }+    var top by remember { mutableFloatStateOf(image.cropTopPct) }+    var right by remember { mutableFloatStateOf(image.cropRightPct) }+    var bottom by remember { mutableFloatStateOf(image.cropBottomPct) }+    val preview = image.copy(cropLeftPct = left, cropTopPct = top, cropRightPct = right, cropBottomPct = bottom, width = 0f, height = 0f)+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text("Crop Image") },+        text = {+            Column {+                Box(Modifier.fillMaxWidth().height(180.dp), contentAlignment = Alignment.Center) { OdfImageView(preview) }+                Spacer(Modifier.height(8.dp))+                CropSlider("Left", left) { left = it }+                CropSlider("Top", top) { top = it }+                CropSlider("Right", right) { right = it }+                CropSlider("Bottom", bottom) { bottom = it }+            }+        },+        confirmButton = { TextButton(onClick = { onApply(left, top, right, bottom); onDismiss() }) { Text("Apply") } },+        dismissButton = {+            Row {+                TextButton(onClick = { onApply(0f, 0f, 0f, 0f); onDismiss() }) { Text("Reset") }+                TextButton(onClick = onDismiss) { Text("Cancel") }+            }+        }+    )+}++@Composable+private fun CropSlider(label: String, value: Float, onChange: (Float) -> Unit) {+    Row(verticalAlignment = Alignment.CenterVertically) {+        Text(label, Modifier.width(64.dp), style = MaterialTheme.typography.labelMedium)+        androidx.compose.material3.Slider(value = value, onValueChange = onChange, valueRange = 0f..0.45f, modifier = Modifier.weight(1f))+        Text("${(value * 100).toInt()}%", Modifier.width(40.dp), style = MaterialTheme.typography.labelSmall)     } } @@ -939,6 +994,32 @@ fun OdfImageView(image: OdfImage, modifier: Modifier = Modifier) {     }     if (bitmap != null) {         val rot = if (image.rotationDegrees != 0f) Modifier.rotate(image.rotationDegrees) else Modifier+        val hasCrop = image.cropLeftPct > 0f || image.cropTopPct > 0f || image.cropRightPct > 0f || image.cropBottomPct > 0f+        if (hasCrop) {+            // Non-destructive crop: draw only the visible source rectangle, scaled to fill. (Phase 5)+            val bw = bitmap.width; val bh = bitmap.height+            val visW = (1f - image.cropLeftPct - image.cropRightPct).coerceIn(0.05f, 1f)+            val visH = (1f - image.cropTopPct - image.cropBottomPct).coerceIn(0.05f, 1f)+            val srcX = (image.cropLeftPct * bw).toInt().coerceIn(0, bw - 1)+            val srcY = (image.cropTopPct * bh).toInt().coerceIn(0, bh - 1)+            val srcW = (visW * bw).toInt().coerceIn(1, bw - srcX)+            val srcH = (visH * bh).toInt().coerceIn(1, bh - srcY)+            val aspect = (srcW.toFloat() / srcH).coerceIn(0.1f, 10f)+            val img = bitmap.asImageBitmap()+            val sized = if (image.width > 0f && image.height > 0f)+                modifier.width((image.width * (160f / 96f)).coerceAtMost(700f).dp).aspectRatio(aspect)+            else modifier.fillMaxWidth().aspectRatio(aspect.coerceIn(0.3f, 4f))+            Canvas(sized.then(rot).padding(vertical = 4.dp)) {+                drawImage(+                    image = img,+                    srcOffset = IntOffset(srcX, srcY),+                    srcSize = IntSize(srcW, srcH),+                    dstOffset = IntOffset.Zero,+                    dstSize = IntSize(size.width.toInt().coerceAtLeast(1), size.height.toInt().coerceAtLeast(1))+                )+            }+            return+        }         val useExplicit = image.width > 0f && image.height > 0f         if (useExplicit) {             // Honor the frame's svg:width/height (px@96dpi -> dp), capped to a readable width. (A2)@@ -1175,17 +1256,20 @@ fun SpreadsheetView(     onCellAlignment: (Int, Int, Int, TextAlign?) -> Unit = { _, _, _, _ -> },     onMergeCells: (Int, Int, Int, Int, Int) -> Unit = { _, _, _, _, _ -> },     onUnmergeCells: (Int, Int, Int) -> Unit = { _, _, _ -> },-    onSort: (Int, Int, Boolean) -> Unit = { _, _, _ -> }+    onSort: (Int, Int, Boolean) -> Unit = { _, _, _ -> },+    onCellSelected: (Int, Int, Int) -> Unit = { _, _, _ -> },+    onFloatingBoundsChange: (Int, Int, Float, Float, Float, Float) -> Unit = { _, _, _, _, _, _ -> },+    onFloatingTextChange: (Int, Int, String) -> Unit = { _, _, _ -> },+    onFloatingDelete: (Int, Int) -> Unit = { _, _ -> } ) {     if (doc.sheets.isEmpty()) { Text("Empty spreadsheet", modifier = Modifier.padding(16.dp)); return }      var selectedSheet by remember { mutableIntStateOf(0) }+    var selectedFloating by remember { mutableIntStateOf(-1) }     var editingCell by remember { mutableStateOf<Triple<Int, Int, Int>?>(null) }     var editText by remember { mutableStateOf(TextFieldValue("")) }     var showRenameSheet by remember { mutableStateOf(false) }     var renameText by remember { mutableStateOf("") }-    var showColorPicker by remember { mutableStateOf(false) }-    var showBgColorPicker by remember { mutableStateOf(false) }     var showSortDialog by remember { mutableStateOf(false) }      Column(modifier = Modifier.fillMaxSize().imePadding()) {@@ -1193,7 +1277,7 @@ fun SpreadsheetView(             Row(verticalAlignment = Alignment.CenterVertically) {                 PrimaryScrollableTabRow(selectedTabIndex = selectedSheet, modifier = Modifier.weight(1f)) {                     doc.sheets.forEachIndexed { index, sheet ->-                        Tab(selected = selectedSheet == index, onClick = { selectedSheet = index; editingCell = null },+                        Tab(selected = selectedSheet == index, onClick = { selectedSheet = index; editingCell = null; selectedFloating = -1; onCellSelected(index, -1, -1) },                             text = { if (isEditMode) Text(sheet.name, Modifier.clickable { renameText = sheet.name; showRenameSheet = true }) else Text(sheet.name) })                     }                 }@@ -1213,9 +1297,10 @@ fun SpreadsheetView(                 onCellTextChange(si, r, c, editText.text)                 if (r + 1 < rowCount) {                     editingCell = Triple(si, r + 1, c)+                    onCellSelected(si, r + 1, c)                     val nextText = doc.sheets[si].rows.getOrNull(r + 1)?.cells?.getOrNull(c)?.let { it.formula ?: it.text } ?: ""                     editText = TextFieldValue(nextText, TextRange(0, nextText.length))-                } else editingCell = null+                } else { editingCell = null; onCellSelected(si, -1, -1) }             }             Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {                 Text("${columnLabel(ci)}${ri + 1}", style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold, modifier = Modifier.padding(end = 8.dp))@@ -1224,19 +1309,7 @@ fun SpreadsheetView(                     keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),                     keyboardActions = KeyboardActions(onNext = { commitAndAdvance() }, onDone = { commitAndAdvance() }),                     colors = TextFieldDefaults.colors(focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant))-                TextButton(onClick = { val (si, r, c) = editingCell!!; onCellTextChange(si, r, c, editText.text); editingCell = null }) { Text("Done") }-            }-            // Cell formatting toolbar-            Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(2.dp)) {-                val (si, r, c) = editingCell!!-                TextButton(onClick = { onCellBold(si, r, c) }) { Text("B", fontWeight = FontWeight.Bold) }-                TextButton(onClick = { onCellItalic(si, r, c) }) { Text("I", fontStyle = FontStyle.Italic) }-                TextButton(onClick = { showColorPicker = true }) { Text("A", color = Color.Red) }-                TextButton(onClick = { showBgColorPicker = true }) { Text("⬛") }-                TextButton(onClick = { onCellAlignment(si, r, c, TextAlign.Start) }) { Text("←") }-                TextButton(onClick = { onCellAlignment(si, r, c, TextAlign.Center) }) { Text("↔") }-                TextButton(onClick = { onCellAlignment(si, r, c, TextAlign.End) }) { Text("→") }-                TextButton(onClick = { onUnmergeCells(si, r, c) }) { Text("⊟") }+                TextButton(onClick = { val (si, r, c) = editingCell!!; onCellTextChange(si, r, c, editText.text); editingCell = null; onCellSelected(si, -1, -1) }) { Text("Done") }             }         } @@ -1265,6 +1338,7 @@ fun SpreadsheetView(             return w.dp         } +        Box(Modifier.fillMaxSize()) {         LazyColumn(modifier = Modifier.fillMaxSize()) {             item {                 Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp)) {@@ -1289,7 +1363,7 @@ fun SpreadsheetView(                                             .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); val t = cell.formula ?: cell.text; editText = TextFieldValue(t, TextRange(0, t.length)) } else 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)@@ -1308,6 +1382,19 @@ fun SpreadsheetView(                 }             }         }+        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 }+            )+        }+        }     }      if (showRenameSheet) {@@ -1316,14 +1403,6 @@ fun SpreadsheetView(             confirmButton = { TextButton(onClick = { onRenameSheet(selectedSheet, renameText); showRenameSheet = false }) { Text("OK") } },             dismissButton = { TextButton(onClick = { showRenameSheet = false }) { Text("Cancel") } })     }-    if (showColorPicker && editingCell != null) {-        val (si, r, c) = editingCell!!-        ColorPickerDialog("Text Color", onColorSelected = { onCellColor(si, r, c, it) }, onDismiss = { showColorPicker = false })-    }-    if (showBgColorPicker && editingCell != null) {-        val (si, r, c) = editingCell!!-        ColorPickerDialog("Background Color", onColorSelected = { onCellBgColor(si, r, c, it) }, onDismiss = { showBgColorPicker = false })-    }     if (showSortDialog) {         val maxC = doc.sheets[selectedSheet].rows.maxOfOrNull { it.cells.size } ?: 1         SortDialog(maxC, onSort = { col, asc -> onSort(selectedSheet, col, asc) }, onDismiss = { showSortDialog = false })@@ -1349,11 +1428,11 @@ fun PresentationView(     onMoveSlideDown: (Int) -> Unit = {},     onElementTextChange: (slideIndex: Int, elementIndex: Int, text: String) -> Unit = { _, _, _ -> },     onAddTextBox: (Int) -> Unit = {},-    onElementBold: (Int, Int) -> Unit = { _, _ -> },-    onElementItalic: (Int, Int) -> Unit = { _, _ -> },-    onElementUnderline: (Int, Int) -> Unit = { _, _ -> },-    onElementColor: (Int, Int, Long?) -> Unit = { _, _, _ -> },-    onElementAlign: (Int, Int, TextAlign?) -> Unit = { _, _, _ -> }+    onElementBoundsChange: (Int, Int, Float, Float, Float, Float) -> Unit = { _, _, _, _, _, _ -> },+    onDeleteElement: (Int, Int) -> Unit = { _, _ -> },+    selectedElement: Int = -1,+    onSlideChange: (Int) -> Unit = {},+    onElementSelected: (Int, Int) -> Unit = { _, _ -> } ) {     if (doc.slides.isEmpty()) { Text("Empty presentation", modifier = Modifier.padding(16.dp)); return } @@ -1361,10 +1440,8 @@ fun PresentationView(     var showGoToSlide by remember { mutableStateOf(false) }     var showSlideshow by remember { mutableStateOf(false) }     var dragAccumulator by remember { mutableFloatStateOf(0f) }-    var focusedEl by remember { mutableIntStateOf(-1) }-    var showSlideColor by remember { mutableStateOf(false) }     currentSlide = currentSlide.coerceIn(0, doc.slides.size - 1)-    LaunchedEffect(currentSlide) { focusedEl = -1 }+    LaunchedEffect(currentSlide) { onSlideChange(currentSlide); onElementSelected(currentSlide, -1) }      Column(modifier = Modifier.fillMaxSize().imePadding()) {         // Main slide with swipe gesture@@ -1385,8 +1462,11 @@ fun PresentationView(                     SlideCard(                         slide = doc.slides[currentSlide],                         editMode = isEditMode,+                        selectedIndex = selectedElement,+                        onSelect = { onElementSelected(currentSlide, it) },                         onElementTextChange = { ei, t -> onElementTextChange(currentSlide, ei, t) },-                        onElementFocus = { focusedEl = it }+                        onBoundsChange = { ei, x, y, w, h -> onElementBoundsChange(currentSlide, ei, x, y, w, h) },+                        onDelete = { ei -> onDeleteElement(currentSlide, ei); onElementSelected(currentSlide, -1) }                     )                 }             }@@ -1406,22 +1486,6 @@ fun PresentationView(             }         } -        // Slide text formatting bar (visible when a text box is focused). (I62)-        if (isEditMode && focusedEl in doc.slides[currentSlide].elements.indices) {-            val el = focusedEl-            Surface(tonalElevation = 3.dp) {-                Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp, vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {-                    TextButton(onClick = { onElementBold(currentSlide, el) }) { Text("B", fontWeight = FontWeight.Bold) }-                    TextButton(onClick = { onElementItalic(currentSlide, el) }) { Text("I", fontStyle = FontStyle.Italic) }-                    TextButton(onClick = { onElementUnderline(currentSlide, el) }) { Text("U", textDecoration = TextDecoration.Underline) }-                    TextButton(onClick = { showSlideColor = true }) { Text("A", color = Color.Red) }-                    TextButton(onClick = { onElementAlign(currentSlide, el, TextAlign.Start) }) { Text("←") }-                    TextButton(onClick = { onElementAlign(currentSlide, el, TextAlign.Center) }) { Text("↔") }-                    TextButton(onClick = { onElementAlign(currentSlide, el, TextAlign.End) }) { Text("→") }-                }-            }-        }-         // Slide thumbnail strip         if (doc.slides.size > 1) {             HorizontalDivider()@@ -1447,10 +1511,6 @@ fun PresentationView(      if (showGoToSlide) GoToSlideDialog(doc.slides.size, onGo = { currentSlide = it }, onDismiss = { showGoToSlide = false })     if (showSlideshow) SlideshowDialog(doc.slides, currentSlide, onSlideChange = { currentSlide = it }, onDismiss = { showSlideshow = false })-    if (showSlideColor && focusedEl in doc.slides[currentSlide].elements.indices) {-        val el = focusedEl-        ColorPickerDialog("Text Color", onColorSelected = { onElementColor(currentSlide, el, it); showSlideColor = false }, onDismiss = { showSlideColor = false })-    } }  /** Editable text field for a slide element, bound by a stable key so it resets per slide/element. (I62) */@@ -1527,12 +1587,20 @@ fun DrawingView(doc: OdfDocument.Drawing) { }  @Composable-private fun SlideCard(slide: OdfSlide, editMode: Boolean = false, onElementTextChange: (Int, String) -> Unit = { _, _ -> }, onElementFocus: (Int) -> Unit = {}) {+private fun SlideCard(+    slide: OdfSlide,+    editMode: Boolean = false,+    selectedIndex: Int = -1,+    onSelect: (Int) -> Unit = {},+    onElementTextChange: (Int, String) -> Unit = { _, _ -> },+    onBoundsChange: (Int, Float, Float, Float, Float) -> Unit = { _, _, _, _, _ -> },+    onDelete: (Int) -> Unit = {}+) {     Column(modifier = Modifier.padding(vertical = 8.dp)) {         Text(slide.name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp))         val (refW, refH) = slideBounds(slide)         Card(modifier = Modifier.fillMaxWidth().aspectRatio((refW / refH).coerceIn(0.5f, 3f)).padding(horizontal = 8.dp), elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)) {-            SlideCanvas(slide, refW, refH, editMode, onElementTextChange, onElementFocus)+            SlideCanvas(slide, refW, refH, editMode, selectedIndex, onSelect, onElementTextChange, onBoundsChange, onDelete)         }         if (slide.notes.isNotEmpty()) {             var expanded by remember { mutableStateOf(false) }@@ -1558,31 +1626,118 @@ private fun slideBounds(slide: OdfSlide): Pair<Float, Float> { }  @Composable-private fun SlideCanvas(slide: OdfSlide, refW: Float, refH: Float, editMode: Boolean = false, onElementTextChange: (Int, String) -> Unit = { _, _ -> }, onElementFocus: (Int) -> Unit = {}) {+private fun SlideCanvas(+    slide: OdfSlide,+    refW: Float,+    refH: Float,+    editMode: Boolean = false,+    selectedIndex: Int = -1,+    onSelect: (Int) -> Unit = {},+    onElementTextChange: (Int, String) -> Unit = { _, _ -> },+    onBoundsChange: (Int, Float, Float, Float, Float) -> Unit = { _, _, _, _, _ -> },+    onDelete: (Int) -> Unit = {}+) {+    FloatingElementLayer(+        elements = slide.elements, refW = refW, refH = refH,+        editMode = editMode, selectedIndex = selectedIndex, keyPrefix = slide.name,+        backgroundColor = slide.backgroundColor,+        onSelect = onSelect, onElementTextChange = onElementTextChange,+        onBoundsChange = onBoundsChange, onDelete = onDelete+    )+}++/**+ * Shared overlay that renders floating elements (frames/shapes) over a reference px@96 canvas,+ * with tap-to-select, drag-to-move, corner resize handles and delete in edit mode. Reused by+ * slides and (Phase 4) spreadsheet floating layers. (Phase 1)+ */+@Composable+fun FloatingElementLayer(+    elements: List<OdfSlideElement>,+    refW: Float,+    refH: Float,+    editMode: Boolean,+    selectedIndex: Int,+    keyPrefix: String,+    backgroundColor: Long? = null,+    interactiveBackground: Boolean = true,+    onSelect: (Int) -> Unit = {},+    onElementTextChange: (Int, String) -> Unit = { _, _ -> },+    onBoundsChange: (Int, Float, Float, Float, Float) -> Unit = { _, _, _, _, _ -> },+    onDelete: (Int) -> Unit = {}+) {     BoxWithConstraints(         Modifier.fillMaxSize()-            .then(slide.backgroundColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)+            .then(backgroundColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)+            .then(if (editMode && interactiveBackground) Modifier.pointerInput(elements.size) { detectTapGestures { onSelect(-1) } } else Modifier)     ) {         val scaleW = maxWidth / refW         val scaleH = maxHeight / refH-        // Scale text proportionally to the slide canvas (pt -> px@96 -> scaled dp). (I60 fix)+        val density = LocalDensity.current.density+        val pxPerModelW = (scaleW.value * density).coerceAtLeast(0.01f)+        val pxPerModelH = (scaleH.value * density).coerceAtLeast(0.01f)+        // Scale text proportionally to the canvas (pt -> px@96 -> scaled dp). (I60)         val fontScale = ((96f / 72f) * (maxWidth.value / refW)).coerceIn(0.2f, 4f)-        slide.elements.forEachIndexed { ei, element ->-            when (element) {-                is OdfSlideElement.Frame -> {-                    val f = element.frame-                    val base = Modifier.offset(x = scaleW * f.x, y = scaleH * f.y).width((scaleW * f.width).coerceAtLeast(1.dp))-                    if (f.image != null) {-                        Box(base.height((scaleH * f.height).coerceAtLeast(1.dp))) { PositionedFrame(f, fontScale, editMode, "${slide.name}#$ei", { onElementTextChange(ei, it) }, { onElementFocus(ei) }) }-                    } else {-                        // Text frames wrap height so large fonts are not truncated.-                        Box(base) { PositionedFrame(f, fontScale, editMode, "${slide.name}#$ei", { onElementTextChange(ei, it) }, { onElementFocus(ei) }) }++        var live by remember(selectedIndex, elements) { mutableStateOf<FloatArray?>(null) }++        elements.forEachIndexed { ei, element ->+            val isSel = editMode && ei == selectedIndex+            val b = if (isSel) (live ?: element.bounds()) else element.bounds()+            val boxW = (scaleW * b[2]).coerceAtLeast(1.dp)+            val boxH = (scaleH * b[3]).coerceAtLeast(1.dp)+            // Text frames wrap height when neither selected nor editing so large fonts aren't truncated.+            val isImageFrame = element is OdfSlideElement.Frame && (element.frame.image != null || element.frame.chart != null)+            val fixedHeight = editMode || isImageFrame || element is OdfSlideElement.Shape+            var base = Modifier.offset(x = scaleW * b[0], y = scaleH * b[1]).width(boxW)+            base = if (fixedHeight) base.height(boxH) else base+            Box(base) {+                Box(+                    Modifier.fillMaxSize()+                        .then(if (editMode && !isSel) Modifier.border(1.dp, MaterialTheme.colorScheme.outlineVariant) else Modifier)+                        .then(if (editMode && !isSel) Modifier.pointerInput(ei) { detectTapGestures { onSelect(ei) } } else Modifier)+                ) {+                    when (element) {+                        is OdfSlideElement.Frame -> PositionedFrame(element.frame, fontScale, isSel, "$keyPrefix#$ei") { onElementTextChange(ei, it) }+                        is OdfSlideElement.Shape -> PositionedShape(element.shape, fontScale, isSel, "$keyPrefix#$ei") { onElementTextChange(ei, it) }                     }                 }-                is OdfSlideElement.Shape -> {-                    val s = element.shape-                    Box(Modifier.offset(x = scaleW * s.x, y = scaleH * s.y).size(width = (scaleW * s.width).coerceAtLeast(1.dp), height = (scaleH * s.height).coerceAtLeast(1.dp))) {-                        PositionedShape(s, fontScale, editMode, "${slide.name}#$ei", { onElementTextChange(ei, it) }, { onElementFocus(ei) })+                if (isSel) {+                    Box(Modifier.fillMaxSize().border(2.dp, MaterialTheme.colorScheme.primary))+                    fun startBounds() = live ?: element.bounds()+                    fun commit() { live?.let { onBoundsChange(ei, it[0], it[1], it[2], it[3]) }; live = null }+                    // Move handle (top center, above the box).+                    ElementHandle(+                        Modifier.align(Alignment.TopCenter).offset(y = (-22).dp),+                        icon = com.vayunmathur.library.R.drawable.drag_handle_24px,+                        onStart = { live = element.bounds() }, onEnd = { commit() }+                    ) { dx, dy ->+                        val c = startBounds()+                        live = floatArrayOf(c[0] + dx / pxPerModelW, c[1] + dy / pxPerModelH, c[2], c[3])+                    }+                    // Corner resize handles.+                    ElementHandle(Modifier.align(Alignment.TopStart).offset((-8).dp, (-8).dp), onStart = { live = element.bounds() }, onEnd = { commit() }) { dx, dy ->+                        val c = startBounds(); val mdx = dx / pxPerModelW; val mdy = dy / pxPerModelH+                        live = floatArrayOf(c[0] + mdx, c[1] + mdy, (c[2] - mdx).coerceAtLeast(20f), (c[3] - mdy).coerceAtLeast(20f))+                    }+                    ElementHandle(Modifier.align(Alignment.TopEnd).offset(8.dp, (-8).dp), onStart = { live = element.bounds() }, onEnd = { commit() }) { dx, dy ->+                        val c = startBounds(); val mdx = dx / pxPerModelW; val mdy = dy / pxPerModelH+                        live = floatArrayOf(c[0], c[1] + mdy, (c[2] + mdx).coerceAtLeast(20f), (c[3] - mdy).coerceAtLeast(20f))+                    }+                    ElementHandle(Modifier.align(Alignment.BottomStart).offset((-8).dp, 8.dp), onStart = { live = element.bounds() }, onEnd = { commit() }) { dx, dy ->+                        val c = startBounds(); val mdx = dx / pxPerModelW; val mdy = dy / pxPerModelH+                        live = floatArrayOf(c[0] + mdx, c[1], (c[2] - mdx).coerceAtLeast(20f), (c[3] + mdy).coerceAtLeast(20f))+                    }+                    ElementHandle(Modifier.align(Alignment.BottomEnd).offset(8.dp, 8.dp), onStart = { live = element.bounds() }, onEnd = { commit() }) { dx, dy ->+                        val c = startBounds(); val mdx = dx / pxPerModelW; val mdy = dy / pxPerModelH+                        live = floatArrayOf(c[0], c[1], (c[2] + mdx).coerceAtLeast(20f), (c[3] + mdy).coerceAtLeast(20f))+                    }+                    // Delete (top end, above the box).+                    Box(Modifier.align(Alignment.TopEnd).offset(x = 12.dp, y = (-24).dp).size(22.dp)+                        .background(MaterialTheme.colorScheme.errorContainer, CircleShape)+                        .border(1.dp, MaterialTheme.colorScheme.error, CircleShape)+                        .clickable { onDelete(ei) }, contentAlignment = Alignment.Center) {+                        Icon(painterResource(com.vayunmathur.library.R.drawable.delete_24px), contentDescription = "Delete element", tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(14.dp))                     }                 }             }@@ -1590,6 +1745,26 @@ private fun SlideCanvas(slide: OdfSlide, refW: Float, refH: Float, editMode: Boo     } } +/** A small draggable selection handle (move/resize). Drag deltas are reported in pixels. (Phase 1) */+@Composable+private fun ElementHandle(modifier: Modifier, icon: Int? = null, onStart: () -> Unit, onEnd: () -> Unit, onDrag: (Float, Float) -> Unit) {+    Box(+        modifier.size(18.dp)+            .background(MaterialTheme.colorScheme.primary, CircleShape)+            .border(1.5.dp, Color.White, CircleShape)+            .pointerInput(Unit) {+                detectDragGestures(+                    onDragStart = { onStart() },+                    onDragEnd = { onEnd() },+                    onDragCancel = { onEnd() }+                ) { change, drag -> change.consume(); onDrag(drag.x, drag.y) }+            },+        contentAlignment = Alignment.Center+    ) {+        if (icon != null) Icon(painterResource(icon), contentDescription = null, tint = Color.White, modifier = Modifier.size(12.dp))+    }+}+ /** Editable in-place text overlay for a slide element. (I62) */ @Composable private fun SlideTextEditor(key: String, paragraphs: List<OdfParagraph>, fontScale: Float, onChange: (String) -> Unit, onFocus: () -> Unit = {}) {@@ -1609,23 +1784,23 @@ private fun SlideTextEditor(key: String, paragraphs: List<OdfParagraph>, fontSca }  @Composable-private fun PositionedFrame(frame: OdfFrame, fontScale: Float, editMode: Boolean = false, editKey: String = "", onTextChange: (String) -> Unit = {}, onFocus: () -> Unit = {}) {+private fun PositionedFrame(frame: OdfFrame, fontScale: Float, editing: Boolean = false, editKey: String = "", onTextChange: (String) -> Unit = {}) {     Box(Modifier.fillMaxSize()         .then(frame.fillColor?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)-        .then(if (editMode && frame.image == null) Modifier.border(1.dp, MaterialTheme.colorScheme.outlineVariant) else Modifier)         .then(frame.strokeColor?.let { Modifier.border((frame.strokeWidth ?: 1f).dp.coerceAtLeast(0.5.dp), Color(it.toInt())) } ?: Modifier)     ) {         frame.image?.let { OdfImageView(it, Modifier.fillMaxSize()) }-        if (editMode && frame.image == null) {-            SlideTextEditor(editKey, frame.paragraphs, fontScale, onTextChange, onFocus)-        } else {+        frame.chart?.let { OdfChartView(it) }+        if (editing && frame.image == null && frame.chart == null) {+            SlideTextEditor(editKey, frame.paragraphs, fontScale, onTextChange)+        } else if (frame.image == null && frame.chart == null) {             Column { for (para in frame.paragraphs) ParagraphView(para, fontSizeMultiplier = fontScale) }         }     } }  @Composable-private fun PositionedShape(shape: OdfShape, fontScale: Float, editMode: Boolean = false, editKey: String = "", onTextChange: (String) -> Unit = {}, onFocus: () -> Unit = {}) {+private fun PositionedShape(shape: OdfShape, fontScale: Float, editing: Boolean = false, editKey: String = "", onTextChange: (String) -> Unit = {}) {     val fillColor = shape.fillColor?.let { Color(it.toInt()) } ?: Color.Transparent     val strokeColor = shape.strokeColor?.let { Color(it.toInt()) } ?: MaterialTheme.colorScheme.outline     val strokeW = shape.strokeWidth ?: 1f@@ -1638,8 +1813,8 @@ private fun PositionedShape(shape: OdfShape, fontScale: Float, editMode: Boolean                 is OdfShape.CustomShape -> { drawRect(fillColor); drawRect(strokeColor, style = Stroke(strokeW)) }             }         }-        if (editMode && shape !is OdfShape.Line) {-            Box(Modifier.padding(4.dp).align(Alignment.Center)) { SlideTextEditor(editKey, shape.text, fontScale, onTextChange, onFocus) }+        if (editing && shape !is OdfShape.Line) {+            Box(Modifier.padding(4.dp).align(Alignment.Center)) { SlideTextEditor(editKey, shape.text, fontScale, onTextChange) }         } else if (shape.text.isNotEmpty()) {             Column(Modifier.padding(4.dp).align(Alignment.Center)) { for (para in shape.text) ParagraphView(para, fontSizeMultiplier = fontScale) }         }
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.ktnew file mode 100644index 0000000000..e73f4fe6bd--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/ui/OfficeBottomBar.kt@@ -0,0 +1,289 @@+package com.vayunmathur.office.ui++import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.LocalContentColor+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextDecoration+import androidx.compose.ui.unit.dp+import com.vayunmathur.office.R+import com.vayunmathur.office.odf.*+import com.vayunmathur.office.util.OfficeViewModel++/** What the shared bottom bar is currently formatting. (Phase 2) */+sealed interface FormatTarget {+    data object None : FormatTarget+    data class TextRun(val runStart: Int, val runEnd: Int, val selStart: Int, val selEnd: Int) : FormatTarget+    data class Cell(val sheet: Int, val row: Int, val col: Int) : FormatTarget+    data class Element(val slide: Int, val element: Int) : FormatTarget+}++/** Which insert actions are available for the current document type. (Phase 2) */+data class DocCaps(+    val insertImage: Boolean = false,+    val insertShape: Boolean = false,+    val insertChart: Boolean = false,+    val insertTable: Boolean = false+)++enum class ShapeKind { RECT, ELLIPSE, LINE }++/** Callbacks the shared bottom bar may invoke. */+data class BottomBarActions(+    val onTextColor: () -> Unit = {},+    val onCellTextColor: () -> Unit = {},+    val onCellBgColor: () -> Unit = {},+    val onSlideTextColor: () -> Unit = {},+    val onFontSize: () -> Unit = {},+    val onInsertImage: () -> Unit = {},+    val onInsertShape: (ShapeKind) -> Unit = {},+    val onInsertChart: () -> Unit = {},+    val onInsertTable: () -> Unit = {},+    val onDeleteElement: () -> Unit = {}+)++@Composable+internal fun FmtIcon(res: Int, active: Boolean, enabled: Boolean, desc: String, onClick: () -> Unit) {+    IconButton(onClick = onClick, enabled = enabled, modifier = Modifier.size(40.dp)) {+        Icon(painterResource(res), contentDescription = desc, tint = if (active && enabled) MaterialTheme.colorScheme.primary else LocalContentColor.current)+    }+}++/**+ * Single shared format + insert bar hosted in the Scaffold bottom bar for all document types.+ * Renders a type-appropriate formatting branch plus a unified Insert menu. (Phase 2)+ */+@Composable+fun OfficeBottomBar(+    document: OdfDocument,+    target: FormatTarget,+    caps: DocCaps,+    viewModel: OfficeViewModel,+    actions: BottomBarActions,+    activeTableBlock: Int = -1,+    activeTableRow: Int = -1,+    activeTableCol: Int = -1+) {+    Surface(tonalElevation = 3.dp) {+        Row(+            Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).navigationBarsPadding().imePadding().padding(horizontal = 4.dp, vertical = 4.dp),+            verticalAlignment = Alignment.CenterVertically+        ) {+            when (document) {+                is OdfDocument.TextDocument -> TextFormatControls(document, target as? FormatTarget.TextRun, viewModel, activeTableBlock, activeTableRow, activeTableCol, actions)+                is OdfDocument.Spreadsheet -> CellFormatControls(target as? FormatTarget.Cell, viewModel, actions)+                is OdfDocument.Presentation -> ElementFormatControls(target as? FormatTarget.Element, viewModel, actions)+                else -> {}+            }+            InsertControl(caps, actions)+        }+    }+}++@Composable+private fun InsertControl(caps: DocCaps, actions: BottomBarActions) {+    if (!(caps.insertImage || caps.insertShape || caps.insertChart || caps.insertTable)) return+    var menu by remember { mutableStateOf(false) }+    var shapeMenu by remember { mutableStateOf(false) }+    Box {+        FmtIcon(com.vayunmathur.library.R.drawable.add_24px, false, true, "Insert") { menu = true }+        DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {+            if (caps.insertImage) DropdownMenuItem(text = { Text("Image…") }, onClick = { menu = false; actions.onInsertImage() })+            if (caps.insertShape) DropdownMenuItem(text = { Text("Shape") }, trailingIcon = { Icon(painterResource(R.drawable.arrow_drop_down_24px), null) }, onClick = { shapeMenu = true })+            if (caps.insertChart) DropdownMenuItem(text = { Text("Chart…") }, onClick = { menu = false; actions.onInsertChart() })+            if (caps.insertTable) DropdownMenuItem(text = { Text("Table…") }, onClick = { menu = false; actions.onInsertTable() })+        }+        DropdownMenu(expanded = shapeMenu, onDismissRequest = { shapeMenu = false }) {+            DropdownMenuItem(text = { Text("Rectangle") }, onClick = { shapeMenu = false; menu = false; actions.onInsertShape(ShapeKind.RECT) })+            DropdownMenuItem(text = { Text("Ellipse") }, onClick = { shapeMenu = false; menu = false; actions.onInsertShape(ShapeKind.ELLIPSE) })+            DropdownMenuItem(text = { Text("Line") }, onClick = { shapeMenu = false; menu = false; actions.onInsertShape(ShapeKind.LINE) })+        }+    }+}++// --- Text document branch (ported from QuickFormatBar) ---++@Composable+private fun TextFormatControls(+    doc: OdfDocument.TextDocument,+    target: FormatTarget.TextRun?,+    viewModel: OfficeViewModel,+    activeTableBlock: Int,+    activeTableRow: Int,+    activeTableCol: Int,+    actions: BottomBarActions+) {+    val enabled = target != null+    val runStart = target?.runStart ?: -1+    val runEnd = target?.runEnd ?: -1+    val selStart = target?.selStart ?: 0+    val selEnd = target?.selEnd ?: 0+    val focusedPara = if (enabled) viewModel.runParagraphIndexAt(runStart, runEnd, selStart) else -1+    val para = (doc.content.getOrNull(focusedPara) as? OdfContentBlock.Paragraph)?.paragraph+    var styleMenu by remember { mutableStateOf(false) }+    var alignMenu by remember { mutableStateOf(false) }+    var tableMenu by remember { mutableStateOf(false) }++    val isBold = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.bold }+    val isItalic = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.italic }+    val isUnderline = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.underline }+    val isStrike = enabled && viewModel.runRangeHasFormat(runStart, runEnd, selStart, selEnd) { it.strikethrough }+    val isBullet = para?.style == ParagraphStyle.LIST_ITEM && para.listType == ListType.BULLET+    val isNumbered = para?.style == ParagraphStyle.LIST_ITEM && para.listType == ListType.NUMBERED++    val styleLabel = when (para?.style) {+        ParagraphStyle.HEADING1 -> "H1"; ParagraphStyle.HEADING2 -> "H2"; ParagraphStyle.HEADING3 -> "H3"; ParagraphStyle.HEADING4 -> "H4"; else -> "Normal"+    }+    val alignIcon = when (para?.alignment) {+        TextAlign.Center -> R.drawable.format_align_center_24px+        TextAlign.End, TextAlign.Right -> R.drawable.format_align_right_24px+        TextAlign.Justify -> R.drawable.format_align_justify_24px+        else -> R.drawable.format_align_left_24px+    }+    fun setStyle(s: ParagraphStyle) { viewModel.mutateRunParagraphs(runStart, runEnd, selStart, selEnd) { it.copy(style = s) } }+    fun setAlign(a: TextAlign) { viewModel.mutateRunParagraphs(runStart, runEnd, selStart, selEnd) { it.copy(alignment = a) } }++    Box {+        TextButton(onClick = { styleMenu = true }, enabled = enabled) {+            Text(styleLabel)+            Icon(painterResource(R.drawable.arrow_drop_down_24px), contentDescription = "Paragraph style")+        }+        DropdownMenu(expanded = styleMenu, onDismissRequest = { styleMenu = false }) {+            DropdownMenuItem(text = { Text("Normal") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.BODY) })+            DropdownMenuItem(text = { Text("Heading 1") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING1) })+            DropdownMenuItem(text = { Text("Heading 2") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING2) })+            DropdownMenuItem(text = { Text("Heading 3") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING3) })+            DropdownMenuItem(text = { Text("Heading 4") }, onClick = { styleMenu = false; setStyle(ParagraphStyle.HEADING4) })+        }+    }+    FmtIcon(R.drawable.format_bold_24px, isBold, enabled, "Bold") { val t = !isBold; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(bold = t) } }+    FmtIcon(R.drawable.format_italic_24px, isItalic, enabled, "Italic") { val t = !isItalic; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(italic = t) } }+    FmtIcon(R.drawable.format_underlined_24px, isUnderline, enabled, "Underline") { val t = !isUnderline; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(underline = t) } }+    FmtIcon(R.drawable.format_strikethrough_24px, isStrike, enabled, "Strikethrough") { val t = !isStrike; viewModel.applyRunSpanStyle(runStart, runEnd, selStart, selEnd) { it.copy(strikethrough = t) } }+    FmtIcon(R.drawable.format_color_text_24px, false, enabled, "Text color") { actions.onTextColor() }+    Box {+        FmtIcon(alignIcon, false, enabled, "Alignment") { alignMenu = true }+        DropdownMenu(expanded = alignMenu, onDismissRequest = { alignMenu = false }) {+            DropdownMenuItem(text = { Text("Left") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_left_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.Start) })+            DropdownMenuItem(text = { Text("Center") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_center_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.Center) })+            DropdownMenuItem(text = { Text("Right") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_right_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.End) })+            DropdownMenuItem(text = { Text("Justify") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_justify_24px), null) }, onClick = { alignMenu = false; setAlign(TextAlign.Justify) })+        }+    }+    FmtIcon(R.drawable.format_list_bulleted_24px, isBullet, enabled, "Bulleted list") { if (focusedPara >= 0) viewModel.toggleListItem(focusedPara) }+    FmtIcon(R.drawable.format_list_numbered_24px, isNumbered, enabled, "Numbered list") { if (focusedPara >= 0) viewModel.toggleNumberedList(focusedPara) }+    FmtIcon(R.drawable.format_indent_increase_24px, false, enabled, "Increase indent") { if (focusedPara >= 0) viewModel.indentParagraph(focusedPara) }+    FmtIcon(R.drawable.format_indent_decrease_24px, false, enabled, "Decrease indent") { if (focusedPara >= 0) viewModel.outdentParagraph(focusedPara) }+    Box {+        val tableEnabled = activeTableBlock >= 0+        TextButton(onClick = { tableMenu = true }) {+            Text("Table")+            Icon(painterResource(R.drawable.arrow_drop_down_24px), contentDescription = "Table options")+        }+        DropdownMenu(expanded = tableMenu, onDismissRequest = { tableMenu = false }) {+            DropdownMenuItem(text = { Text("Insert table") }, onClick = { tableMenu = false; actions.onInsertTable() })+            HorizontalDivider()+            DropdownMenuItem(text = { Text("Insert row below") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableAddRow(activeTableBlock, activeTableRow) })+            DropdownMenuItem(text = { Text("Insert column right") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableAddColumn(activeTableBlock, activeTableCol) })+            DropdownMenuItem(text = { Text("Delete row") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableDeleteRow(activeTableBlock, activeTableRow) })+            DropdownMenuItem(text = { Text("Delete column") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.textTableDeleteColumn(activeTableBlock, activeTableCol) })+            HorizontalDivider()+            DropdownMenuItem(text = { Text("Bold cell") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.setTextTableCellSpanFormat(activeTableBlock, activeTableRow, activeTableCol) { it.copy(bold = !it.bold) } })+            DropdownMenuItem(text = { Text("Italic cell") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.setTextTableCellSpanFormat(activeTableBlock, activeTableRow, activeTableCol) { it.copy(italic = !it.italic) } })+            DropdownMenuItem(text = { Text("Merge with right") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.mergeTextTableCells(activeTableBlock, activeTableRow, activeTableCol, activeTableRow, activeTableCol + 1) })+            DropdownMenuItem(text = { Text("Merge with below") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.mergeTextTableCells(activeTableBlock, activeTableRow, activeTableCol, activeTableRow + 1, activeTableCol) })+            DropdownMenuItem(text = { Text("Unmerge cell") }, enabled = tableEnabled, onClick = { tableMenu = false; viewModel.unmergeTextTableCells(activeTableBlock, activeTableRow, activeTableCol) })+        }+    }+    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("Font size…") }, onClick = { moreMenu = false; actions.onFontSize() })+            DropdownMenuItem(text = { Text("Clear formatting") }, onClick = { moreMenu = false; viewModel.clearRunFormatting(runStart, runEnd, selStart, selEnd) })+            HorizontalDivider()+            DropdownMenuItem(text = { Text("Demote list item") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; if (focusedPara >= 0) viewModel.changeListLevel(focusedPara, 1) })+            DropdownMenuItem(text = { Text("Promote list item") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; if (focusedPara >= 0) viewModel.changeListLevel(focusedPara, -1) })+            DropdownMenuItem(text = { Text("Restart numbering") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; if (focusedPara >= 0) viewModel.restartNumbering(focusedPara) })+            HorizontalDivider()+            DropdownMenuItem(text = { Text("Duplicate paragraph") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; viewModel.duplicateParagraph(focusedPara) })+            DropdownMenuItem(text = { Text("Move paragraph up") }, enabled = focusedPara > 0, onClick = { moreMenu = false; viewModel.moveParagraphUp(focusedPara) })+            DropdownMenuItem(text = { Text("Move paragraph down") }, enabled = focusedPara >= 0, onClick = { moreMenu = false; viewModel.moveParagraphDown(focusedPara) })+            DropdownMenuItem(text = { Text("Delete paragraph", color = MaterialTheme.colorScheme.error) }, enabled = focusedPara >= 0, onClick = { moreMenu = false; viewModel.deleteParagraph(focusedPara) })+        }+    }+}++// --- Spreadsheet cell branch ---++@Composable+private fun CellFormatControls(target: FormatTarget.Cell?, viewModel: OfficeViewModel, actions: BottomBarActions) {+    val enabled = target != null+    val s = target?.sheet ?: -1+    val r = target?.row ?: -1+    val c = target?.col ?: -1+    var alignMenu by remember { mutableStateOf(false) }+    FmtIcon(R.drawable.format_bold_24px, false, enabled, "Bold") { if (enabled) viewModel.setCellBold(s, r, c) }+    FmtIcon(R.drawable.format_italic_24px, false, enabled, "Italic") { if (enabled) viewModel.setCellItalic(s, r, c) }+    FmtIcon(R.drawable.format_color_text_24px, false, enabled, "Text color") { actions.onCellTextColor() }+    TextButton(onClick = { actions.onCellBgColor() }, enabled = enabled) { Text("Fill") }+    Box {+        FmtIcon(R.drawable.format_align_left_24px, false, enabled, "Alignment") { alignMenu = true }+        DropdownMenu(expanded = alignMenu, onDismissRequest = { alignMenu = false }) {+            DropdownMenuItem(text = { Text("Left") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_left_24px), null) }, onClick = { alignMenu = false; if (enabled) viewModel.setCellAlignment(s, r, c, TextAlign.Start) })+            DropdownMenuItem(text = { Text("Center") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_center_24px), null) }, onClick = { alignMenu = false; if (enabled) viewModel.setCellAlignment(s, r, c, TextAlign.Center) })+            DropdownMenuItem(text = { Text("Right") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_right_24px), null) }, onClick = { alignMenu = false; if (enabled) viewModel.setCellAlignment(s, r, c, TextAlign.End) })+        }+    }+    TextButton(onClick = { if (enabled) viewModel.unmergeCells(s, r, c) }, enabled = enabled) { Text("Unmerge") }+}++// --- Presentation element branch ---++@Composable+private fun ElementFormatControls(target: FormatTarget.Element?, viewModel: OfficeViewModel, actions: BottomBarActions) {+    val enabled = target != null+    val s = target?.slide ?: -1+    val e = target?.element ?: -1+    var alignMenu by remember { mutableStateOf(false) }+    FmtIcon(R.drawable.format_bold_24px, false, enabled, "Bold") { if (enabled) viewModel.toggleSlideElementBold(s, e) }+    FmtIcon(R.drawable.format_italic_24px, false, enabled, "Italic") { if (enabled) viewModel.toggleSlideElementItalic(s, e) }+    FmtIcon(R.drawable.format_underlined_24px, false, enabled, "Underline") { if (enabled) viewModel.toggleSlideElementUnderline(s, e) }+    FmtIcon(R.drawable.format_color_text_24px, false, enabled, "Text color") { actions.onSlideTextColor() }+    Box {+        FmtIcon(R.drawable.format_align_left_24px, false, enabled, "Alignment") { alignMenu = true }+        DropdownMenu(expanded = alignMenu, onDismissRequest = { alignMenu = false }) {+            DropdownMenuItem(text = { Text("Left") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_left_24px), null) }, onClick = { alignMenu = false; if (enabled) viewModel.setSlideElementAlignment(s, e, TextAlign.Start) })+            DropdownMenuItem(text = { Text("Center") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_center_24px), null) }, onClick = { alignMenu = false; if (enabled) viewModel.setSlideElementAlignment(s, e, TextAlign.Center) })+            DropdownMenuItem(text = { Text("Right") }, leadingIcon = { Icon(painterResource(R.drawable.format_align_right_24px), null) }, onClick = { alignMenu = false; if (enabled) viewModel.setSlideElementAlignment(s, e, TextAlign.End) })+        }+    }+    FmtIcon(com.vayunmathur.library.R.drawable.delete_24px, false, enabled, "Delete element") { if (enabled) actions.onDeleteElement() }+}
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 2184af277e..8331da59bd 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -552,6 +552,17 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         updateDocument(doc.copy(content = content, images = doc.images + (path to bytes)))     } +    /** 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+        val block = doc.content.getOrNull(blockIndex) as? OdfContentBlock.Image ?: return+        val content = doc.content.toMutableList()+        content[blockIndex] = OdfContentBlock.Image(block.image.copy(+            cropLeftPct = left, cropTopPct = top, cropRightPct = right, cropBottomPct = bottom+        ))+        updateDocument(doc.copy(content = content))+    }+     /** Inserts a horizontal rule (rendered as a bordered empty paragraph) (B19). */     fun insertHorizontalLine(blockIndex: Int) {         val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.TextDocument ?: return@@ -1239,6 +1250,117 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         updateDocument(doc.copy(slides = slides))     } +    /** Adds a shape to a slide at a default centered rect. kind = "rect"|"ellipse"|"line". (Phase 3) */+    fun addShapeToSlide(slideIndex: Int, kind: String) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return+        val slides = doc.slides.toMutableList()+        val slide = slides.getOrNull(slideIndex) ?: return+        val x = 329f; val y = 247f; val w = 400f; val h = 300f+        val shape: OdfShape = when (kind) {+            "ellipse" -> OdfShape.Ellipse(x, y, w, h, fillColor = 0xFFB3D1FFL, strokeColor = 0xFF1F6FC0L, strokeWidth = 2f)+            "line" -> OdfShape.Line(x, y, w, 0f, strokeColor = 0xFF333333L, strokeWidth = 2f, x2 = x + w, y2 = y)+            else -> OdfShape.Rect(x, y, w, h, fillColor = 0xFFB3D1FFL, strokeColor = 0xFF1F6FC0L, strokeWidth = 2f)+        }+        slides[slideIndex] = slide.copy(elements = slide.elements + OdfSlideElement.Shape(shape))+        updateDocument(doc.copy(slides = slides))+    }++    /** Inserts an image as a floating frame on a slide. (Phase 3) */+    fun insertImageIntoSlide(slideIndex: Int, fileName: String, bytes: ByteArray) {+        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 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))+        updateDocument(doc.copy(slides = slides, images = doc.images + (path to bytes)))+    }++    /** Inserts a chart as a floating frame on a slide. (Phase 3) */+    fun insertChartIntoSlide(slideIndex: Int, chart: OdfChart) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Presentation ?: return+        val slides = doc.slides.toMutableList()+        val slide = slides.getOrNull(slideIndex) ?: return+        val frame = OdfFrame(x = 250f, y = 180f, width = 520f, height = 360f, paragraphs = emptyList(), chart = chart)+        slides[slideIndex] = slide.copy(elements = slide.elements + OdfSlideElement.Frame(frame))+        updateDocument(doc.copy(slides = slides))+    }++    // --- Spreadsheet floating objects (Phase 4) ---++    private fun mutateSheetFloating(sheetIndex: Int, transform: (List<OdfSlideElement>) -> List<OdfSlideElement>) {+        val doc = (_state.value as? ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return+        val sheets = doc.sheets.toMutableList()+        val sheet = sheets.getOrNull(sheetIndex) ?: return+        sheets[sheetIndex] = sheet.copy(floating = transform(sheet.floating))+        updateDocument(doc.copy(sheets = sheets))+    }++    fun addShapeToSheet(sheetIndex: Int, kind: String) {+        val x = 120f; val y = 120f; val w = 300f; val h = 200f+        val shape: OdfShape = when (kind) {+            "ellipse" -> OdfShape.Ellipse(x, y, w, h, fillColor = 0xFFB3D1FFL, strokeColor = 0xFF1F6FC0L, strokeWidth = 2f)+            "line" -> OdfShape.Line(x, y, w, 0f, strokeColor = 0xFF333333L, strokeWidth = 2f, x2 = x + w, y2 = y)+            else -> OdfShape.Rect(x, y, w, h, fillColor = 0xFFB3D1FFL, strokeColor = 0xFF1F6FC0L, strokeWidth = 2f)+        }+        mutateSheetFloating(sheetIndex) { it + OdfSlideElement.Shape(shape) }+    }++    fun insertImageIntoSheet(sheetIndex: Int, fileName: String, bytes: ByteArray) {+        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 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))+        updateDocument(doc.copy(sheets = sheets, images = doc.images + (path to bytes)))+    }++    fun insertChartIntoSheet(sheetIndex: Int, chart: OdfChart) {+        val frame = OdfFrame(x = 80f, y = 80f, width = 480f, height = 320f, paragraphs = emptyList(), chart = chart)+        mutateSheetFloating(sheetIndex) { it + OdfSlideElement.Frame(frame) }+    }++    fun setSheetElementBounds(sheetIndex: Int, elementIndex: Int, x: Float, y: Float, w: Float, h: Float) {+        mutateSheetFloating(sheetIndex) { list ->+            if (elementIndex !in list.indices) list+            else list.toMutableList().also { it[elementIndex] = setElementBounds(it[elementIndex], x, y, w, h) }+        }+    }++    fun deleteSheetElement(sheetIndex: Int, elementIndex: Int) {+        mutateSheetFloating(sheetIndex) { list -> list.filterIndexed { i, _ -> i != elementIndex } }+    }++    fun updateSheetElementText(sheetIndex: Int, elementIndex: Int, newText: String) {+        mutateSheetFloating(sheetIndex) { list ->+            if (elementIndex !in list.indices) return@mutateSheetFloating list+            list.toMutableList().also { it[elementIndex] = setSlideElementTextOn(it[elementIndex], newText) }+        }+    }++    private fun setSlideElementTextOn(el: OdfSlideElement, newText: String): OdfSlideElement {+        fun rebuild(old: List<OdfParagraph>): List<OdfParagraph> {+            val template = old.firstOrNull()?.spans?.firstOrNull()?.copy(text = "") ?: OdfSpan(text = "")+            val style = old.firstOrNull()?.style ?: ParagraphStyle.BODY+            return newText.split("\n").map { line -> OdfParagraph(listOf(template.copy(text = line)), style = style) }+        }+        return when (el) {+            is OdfSlideElement.Frame -> OdfSlideElement.Frame(el.frame.copy(paragraphs = rebuild(el.frame.paragraphs)))+            is OdfSlideElement.Shape -> {+                val s = el.shape; val t = rebuild(s.text)+                OdfSlideElement.Shape(when (s) {+                    is OdfShape.Rect -> s.copy(text = t); is OdfShape.Ellipse -> s.copy(text = t)+                    is OdfShape.Line -> s.copy(text = t); is OdfShape.CustomShape -> s.copy(text = t)+                })+            }+        }+    }+     private fun elementParas(el: OdfSlideElement): List<OdfParagraph> = when (el) {         is OdfSlideElement.Frame -> el.frame.paragraphs         is OdfSlideElement.Shape -> el.shape.text@@ -1298,6 +1420,30 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application)         updateDocument(doc.copy(slides = slides))     } +    /** Moves/resizes a slide element (frame or shape). Coordinates are px@96. (Phase 1) */+    fun setSlideElementBounds(slideIndex: Int, elementIndex: Int, x: Float, y: Float, w: Float, h: 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 elements = slide.elements.toMutableList()+        val el = elements.getOrNull(elementIndex) ?: return+        elements[elementIndex] = setElementBounds(el, x, y, w, h)+        slides[slideIndex] = slide.copy(elements = elements)+        updateDocument(doc.copy(slides = slides))+    }++    /** Removes a slide element. (Phase 1) */+    fun deleteSlideElement(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+        if (elementIndex !in slide.elements.indices) return+        val elements = slide.elements.toMutableList()+        elements.removeAt(elementIndex)+        slides[slideIndex] = slide.copy(elements = elements)+        updateDocument(doc.copy(slides = slides))+    }+     // --- CSV export ---      fun exportCsv(): String {