Modern Apps git

← Modern-Apps.git

office: significant improvements to rendering and editing UX

Commit
cd1239407f2d49e1793f17f03d195b126ba92225
Author
Vayun Mathur <[email protected]>
When
2026-06-20 22:38 UTC (5 months ago)
Parents
9d1d325

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 6ac8750fe6..937fd84c19 100644--- a/office/src/main/java/com/vayunmathur/office/MainActivity.kt+++ b/office/src/main/java/com/vayunmathur/office/MainActivity.kt@@ -19,6 +19,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -123,13 +124,17 @@ class MainActivity : ComponentActivity() {             val filePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->                 uri?.let { documentUri = it; viewModel.loadDocument(it, it.lastPathSegment ?: "document") }             }+            val csvImportLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+                uri?.let { documentUri = it; viewModel.loadCsv(it, it.lastPathSegment ?: "import.csv") }+            }              OfficeLightTheme {                 Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {                     when (val s = state) {                         is OfficeViewModel.ViewState.Empty -> InitialScreen(                             viewModel = viewModel,-                            onOpenDocument = { filePickerLauncher.launch(odfMimeTypes) }+                            onOpenDocument = { filePickerLauncher.launch(odfMimeTypes) },+                            onImportCsv = { csvImportLauncher.launch(arrayOf("text/csv", "text/comma-separated-values", "text/plain", "*/*")) }                         )                         is OfficeViewModel.ViewState.Loading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }                         is OfficeViewModel.ViewState.Loaded -> DocumentScreen(@@ -151,7 +156,7 @@ class MainActivity : ComponentActivity() { }  @Composable-fun InitialScreen(viewModel: OfficeViewModel, onOpenDocument: () -> Unit) {+fun InitialScreen(viewModel: OfficeViewModel, onOpenDocument: () -> Unit, onImportCsv: () -> Unit = {}) {     Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) {         Spacer(Modifier.height(48.dp))         Text("Office", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)@@ -167,6 +172,8 @@ fun InitialScreen(viewModel: OfficeViewModel, onOpenDocument: () -> Unit) {             OutlinedButton(onClick = { viewModel.createNewSpreadsheet() }, Modifier.weight(1f)) { Text("New Sheet") }             OutlinedButton(onClick = { viewModel.createNewPresentation() }, Modifier.weight(1f)) { Text("New Slides") }         }+        Spacer(Modifier.height(8.dp))+        OutlinedButton(onClick = onImportCsv, modifier = Modifier.fillMaxWidth()) { Text("Import CSV") }     } } @@ -183,6 +190,8 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:     var activeTableBlock by remember { mutableIntStateOf(-1) }     var activeTableRow by remember { mutableIntStateOf(-1) }     var activeTableCol by remember { mutableIntStateOf(-1) }+    var showChartEditor by remember { mutableStateOf(false) }+    var editingChartBlock by remember { mutableIntStateOf(-1) }     var showUnsavedDialog by remember { mutableStateOf(false) }     var showReplaceBar by remember { mutableStateOf(false) }     var replaceText by remember { mutableStateOf("") }@@ -192,17 +201,19 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:     var showInsertTable by remember { mutableStateOf(false) }     var showInsertLink by remember { mutableStateOf(false) }     var showAddBookmark by remember { mutableStateOf(false) }+    var showSpecialChars by remember { mutableStateOf(false) }+    var showFootnote by remember { mutableStateOf(false) }+    var showComment by remember { mutableStateOf(false) }+    var showHeaderFooter by remember { mutableStateOf(false) }+    var matchCase by remember { mutableStateOf(false) }+    var wholeWord by remember { mutableStateOf(false) }     var showTimer by remember { mutableStateOf(false) }     var timerSeconds by remember { mutableIntStateOf(0) }     var selStart by remember { mutableIntStateOf(0) }     var selEnd by remember { mutableIntStateOf(0) }     var fileMenu by remember { mutableStateOf(false) }-    var editMenu by remember { mutableStateOf(false) }     var insertMenu by remember { mutableStateOf(false) }-    var formatMenu by remember { mutableStateOf(false) }     var viewMenu by remember { mutableStateOf(false) }-    var styleMenu by remember { mutableStateOf(false) }-    var alignMenu by remember { mutableStateOf(false) }      val isEditMode by viewModel.isEditMode.collectAsState()     val hasUnsavedChanges by viewModel.hasUnsavedChanges.collectAsState()@@ -235,6 +246,21 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:             context.contentResolver.openOutputStream(it)?.writer()?.use { w -> w.write(csv) }         }     }+    val imagePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->+        uri?.let {+            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)+            } catch (_: Exception) {}+        }+    }+    val flatExportLauncher = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/xml")) { uri ->+        uri?.let {+            val xml = viewModel.exportFlat()+            if (xml.isNotEmpty()) context.contentResolver.openOutputStream(it)?.writer()?.use { w -> w.write(xml) }+        }+    }      // Presentation timer     LaunchedEffect(showTimer) {@@ -291,6 +317,7 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                             }                         },                         actions = {+                            if (canEdit) IconButton(onClick = { showSearch = !showSearch }) { Icon(painterResource(com.vayunmathur.library.R.drawable.outline_search_24), contentDescription = "Search") }                             IconButton(onClick = { viewModel.undo() }, enabled = canUndo) { Icon(painterResource(com.vayunmathur.library.R.drawable.undo_24px), contentDescription = "Undo") }                             IconButton(onClick = { viewModel.redo() }, enabled = canRedo) { Icon(painterResource(R.drawable.redo_24px), contentDescription = "Redo") }                             IconButton(onClick = { viewModel.save() }, enabled = hasUnsavedChanges && !isSaving) {@@ -312,43 +339,35 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                                         DropdownMenuItem(text = { Text(stringResource(R.string.share)) }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.share_24px), null) }, onClick = { fileMenu = false; context.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { type = "*/*"; putExtra(Intent.EXTRA_STREAM, uri); addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) }, null)) })                                     }                                     DropdownMenuItem(text = { Text("Export as Text") }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.outline_file_download_24), null) }, onClick = { fileMenu = false; val t = viewModel.exportAsPlainText(); if (t.isNotEmpty()) context.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { type = "text/plain"; putExtra(Intent.EXTRA_TEXT, t) }, null)) })+                                    DropdownMenuItem(text = { Text("Export flat ODF…") }, onClick = { fileMenu = false; val ext = when { isTextDoc -> ".fodt"; isSpreadsheet -> ".fods"; isPresentation -> ".fodp"; else -> ".fodg" }; flatExportLauncher.launch(document.title.substringBeforeLast('.') + ext) })                                     if (isSpreadsheet) DropdownMenuItem(text = { Text("Export as CSV") }, onClick = { fileMenu = false; csvExportLauncher.launch("export.csv") })                                     HorizontalDivider()                                     DropdownMenuItem(text = { Text(stringResource(R.string.document_info)) }, onClick = { fileMenu = false; showMetadata = true })                                     DropdownMenuItem(text = { Text("Settings") }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.settings_24px), null) }, onClick = { fileMenu = false; showSettings = true })                                 }                             }-                            // Edit-                            Box {-                                TextButton(onClick = { editMenu = true }) { Text("Edit") }-                                DropdownMenu(expanded = editMenu, onDismissRequest = { editMenu = false }) {-                                    DropdownMenuItem(text = { Text(stringResource(R.string.search)) }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.outline_search_24), null) }, onClick = { editMenu = false; showSearch = true })-                                    if (isTextDoc) {-                                        HorizontalDivider()-                                        DropdownMenuItem(text = { Text("Duplicate paragraph") }, enabled = focusedPara >= 0, onClick = { editMenu = false; viewModel.duplicateParagraph(focusedPara) })-                                        DropdownMenuItem(text = { Text("Move paragraph up") }, enabled = focusedPara > 0, onClick = { editMenu = false; viewModel.moveParagraphUp(focusedPara) })-                                        DropdownMenuItem(text = { Text("Move paragraph down") }, enabled = focusedPara >= 0, onClick = { editMenu = false; viewModel.moveParagraphDown(focusedPara) })-                                        DropdownMenuItem(text = { Text("Delete paragraph", color = MaterialTheme.colorScheme.error) }, enabled = focusedPara >= 0, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.delete_24px), null) }, onClick = { editMenu = false; viewModel.deleteParagraph(focusedPara) })-                                    }-                                }-                            }+                            // Edit menu removed: Search moved to a top-bar icon; paragraph ops live in the bottom bar's ⋮ menu.                             // Insert                             if (isTextDoc) Box {                                 TextButton(onClick = { insertMenu = true }) { Text("Insert") }                                 DropdownMenu(expanded = insertMenu, onDismissRequest = { insertMenu = false }) {                                     DropdownMenuItem(text = { Text("Paragraph") }, leadingIcon = { Icon(painterResource(com.vayunmathur.library.R.drawable.add_24px), null) }, onClick = { insertMenu = false; viewModel.addParagraphAfter(maxOf(0, focusedPara)) })+                                    DropdownMenuItem(text = { Text("Image…") }, onClick = { insertMenu = false; imagePickerLauncher.launch("image/*") })                                     DropdownMenuItem(text = { Text("Hyperlink") }, onClick = { insertMenu = false; showInsertLink = true })+                                    DropdownMenuItem(text = { Text("Chart") }, onClick = { insertMenu = false; editingChartBlock = -1; showChartEditor = true })+                                    DropdownMenuItem(text = { Text("Special character…") }, onClick = { insertMenu = false; showSpecialChars = true })+                                    DropdownMenuItem(text = { Text("Date") }, onClick = { insertMenu = false; if (activeRunStart >= 0) viewModel.insertTextInRun(activeRunStart, activeRunEnd, selStart, java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault()).format(java.util.Date())) })+                                    DropdownMenuItem(text = { Text("Time") }, onClick = { insertMenu = false; if (activeRunStart >= 0) viewModel.insertTextInRun(activeRunStart, activeRunEnd, selStart, java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault()).format(java.util.Date())) })                                     DropdownMenuItem(text = { Text("Bookmark") }, onClick = { insertMenu = false; showAddBookmark = true })+                                    DropdownMenuItem(text = { Text("Footnote…") }, onClick = { insertMenu = false; showFootnote = true })+                                    DropdownMenuItem(text = { Text("Comment…") }, enabled = focusedPara >= 0, onClick = { insertMenu = false; showComment = true })+                                    DropdownMenuItem(text = { Text("Table of contents") }, onClick = { insertMenu = false; viewModel.insertTableOfContents() })+                                    DropdownMenuItem(text = { Text("Header & footer…") }, onClick = { insertMenu = false; showHeaderFooter = true })+                                    DropdownMenuItem(text = { Text("Horizontal line") }, onClick = { insertMenu = false; viewModel.insertHorizontalLine(maxOf(0, focusedPara)) })                                     DropdownMenuItem(text = { Text("Page break") }, onClick = { insertMenu = false; viewModel.insertPageBreak(maxOf(0, focusedPara)) })                                 }                             }-                            // Format-                            if (isTextDoc) Box {-                                TextButton(onClick = { formatMenu = true }) { Text("Format") }-                                DropdownMenu(expanded = formatMenu, onDismissRequest = { formatMenu = false }) {-                                    DropdownMenuItem(text = { Text(stringResource(R.string.font_size)) }, enabled = focusedPara >= 0, onClick = { formatMenu = false; showFontSizePicker = true })-                                }-                            }+                            // Format menu removed: font size, clear formatting, and list level/restart moved to the bottom bar's ⋮ menu.                             // View                             Box {                                 TextButton(onClick = { viewMenu = true }) { Text("View") }@@ -361,6 +380,16 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                             }                         }                     }+                    AnimatedVisibility(visible = showTimer && isPresentation) {+                        Surface(color = MaterialTheme.colorScheme.secondaryContainer) {+                            Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {+                                Text("⏱ %02d:%02d".format(timerSeconds / 60, timerSeconds % 60), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSecondaryContainer)+                                Spacer(Modifier.weight(1f))+                                TextButton(onClick = { timerSeconds = 0 }) { Text("Reset") }+                                TextButton(onClick = { showTimer = false }) { Text("Stop") }+                            }+                        }+                    }                     AnimatedVisibility(visible = showSearch) {                         Column {                             TextField(value = searchQuery, onValueChange = { searchQuery = it }, placeholder = { Text(stringResource(R.string.search_hint)) }, singleLine = true,@@ -373,11 +402,17 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                                     }                                 })                             AnimatedVisibility(visible = showReplaceBar && searchQuery.isNotEmpty()) {-                                Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {-                                    TextField(value = replaceText, onValueChange = { replaceText = it }, placeholder = { Text(stringResource(R.string.replace_hint)) }, singleLine = true, modifier = Modifier.weight(1f),-                                        colors = TextFieldDefaults.colors(focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant))-                                    TextButton(onClick = { viewModel.replaceInDocument(searchQuery, replaceText, false) }) { Text("One") }-                                    TextButton(onClick = { val n = viewModel.replaceInDocument(searchQuery, replaceText, true); if (n > 0) searchQuery = "" }) { Text("All") }+                                Column {+                                    Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {+                                        TextField(value = replaceText, onValueChange = { replaceText = it }, placeholder = { Text(stringResource(R.string.replace_hint)) }, singleLine = true, modifier = Modifier.weight(1f),+                                            colors = TextFieldDefaults.colors(focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant, unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant))+                                        TextButton(onClick = { viewModel.replaceInDocument(searchQuery, replaceText, false, matchCase, wholeWord) }) { Text("One") }+                                        TextButton(onClick = { val n = viewModel.replaceInDocument(searchQuery, replaceText, true, matchCase, wholeWord); if (n > 0) searchQuery = "" }) { Text("All") }+                                    }+                                    Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {+                                        TextButton(onClick = { matchCase = !matchCase }) { Text(if (matchCase) "☑ Case" else "☐ Case") }+                                        TextButton(onClick = { wholeWord = !wholeWord }) { Text(if (wholeWord) "☑ Word" else "☐ Word") }+                                    }                                 }                             }                         }@@ -394,16 +429,17 @@ 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 })+                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 })             }         ) { paddingValues ->             Box(Modifier.padding(paddingValues)) {                 when (document) {                     is OdfDocument.TextDocument -> TextDocumentView(doc = document, searchQuery = searchQuery, fontSizeMultiplier = fontSizeMultiplier, listState = listState,-                        onRunSelectionChange = { rs, re, gs, ge -> activeRunStart = rs; activeRunEnd = re; selStart = gs; selEnd = ge },+                        onRunSelectionChange = { rs, re, gs, ge -> activeRunStart = rs; activeRunEnd = re; selStart = gs; selEnd = ge; activeTableBlock = -1; activeTableRow = -1; activeTableCol = -1 },                         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 })+                        onCellFocus = { bi, r, c -> activeTableBlock = bi; activeTableRow = r; activeTableCol = c },+                        onChartClick = { bi -> editingChartBlock = bi; showChartEditor = true })                     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) },@@ -415,14 +451,18 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:                         onSort = { s, col, asc -> viewModel.sortRows(s, col, asc) })                     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) })+                        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) })                     is OdfDocument.Drawing -> DrawingView(document)                 }             }         }     } -    if (showMetadata) MetadataDialog(metadata = document.metadata, onDismiss = { showMetadata = false })+    if (showMetadata) MetadataDialog(metadata = document.metadata, onSave = { m -> viewModel.updateMetadata { m } }, onDismiss = { showMetadata = false })     if (showUnsavedDialog) AlertDialog(onDismissRequest = { showUnsavedDialog = false }, title = { Text(stringResource(R.string.unsaved_changes)) },         text = { Text(stringResource(R.string.unsaved_changes_message)) },         confirmButton = { TextButton(onClick = { showUnsavedDialog = false; onBack() }) { Text(stringResource(R.string.discard), color = MaterialTheme.colorScheme.error) } },@@ -436,10 +476,30 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity:     if (showInsertTable) InsertTableDialog(onInsert = { r, c -> viewModel.insertTable(maxOf(0, focusedPara), r, c) }, onDismiss = { showInsertTable = false })     if (showInsertLink) InsertHyperlinkDialog(onInsert = { t, u -> viewModel.insertHyperlink(maxOf(0, focusedPara), t, u) }, onDismiss = { showInsertLink = false })     if (showAddBookmark) AddBookmarkDialog(onAdd = { viewModel.addBookmark(it, maxOf(0, focusedPara)) }, onDismiss = { showAddBookmark = false })+    if (showSpecialChars) SpecialCharsDialog(onPick = { ch -> if (activeRunStart >= 0) viewModel.insertTextInRun(activeRunStart, activeRunEnd, selStart, ch) }, onDismiss = { showSpecialChars = false })+    if (showFootnote) FootnoteDialog(onAdd = { body -> if (activeRunStart >= 0) viewModel.insertFootnote(activeRunStart, activeRunEnd, selStart, body) }, onDismiss = { showFootnote = false })+    if (showComment) CommentDialog(onAdd = { author, text -> if (focusedPara >= 0) viewModel.insertComment(focusedPara, author, text) }, onDismiss = { showComment = false })+    if (showHeaderFooter) {+        val td = document as? OdfDocument.TextDocument+        HeaderFooterDialog(+            initialHeader = td?.headerParagraphs?.joinToString("\n") { p -> p.spans.joinToString("") { it.text } } ?: "",+            initialFooter = td?.footerParagraphs?.joinToString("\n") { p -> p.spans.joinToString("") { it.text } } ?: "",+            onSave = { h, f -> viewModel.setHeaderText(h); viewModel.setFooterText(f) },+            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 }+        )+    } }  @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) {+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@@ -513,6 +573,29 @@ private fun QuickFormatBar(document: OdfDocument, runStart: Int, runEnd: Int, se                     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) })                 }             }         }@@ -526,26 +609,45 @@ private fun QuickFormatBar(document: OdfDocument, runStart: Int, runEnd: Int, se }  @Composable-private fun MetadataDialog(metadata: OdfMetadata, onDismiss: () -> Unit) {+private fun MetadataDialog(metadata: OdfMetadata, onSave: (OdfMetadata) -> Unit, onDismiss: () -> Unit) {+    var title by remember { mutableStateOf(metadata.title ?: "") }+    var author by remember { mutableStateOf(metadata.author ?: "") }+    var subject by remember { mutableStateOf(metadata.subject ?: "") }+    var description by remember { mutableStateOf(metadata.description ?: "") }+    var keywords by remember { mutableStateOf(metadata.keywords.joinToString(", ")) }     AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(R.string.document_info)) },         text = {-            Column {-                metadata.title?.let { MetadataRow(stringResource(R.string.meta_title), it) }-                metadata.author?.let { MetadataRow(stringResource(R.string.meta_author), it) }-                metadata.creator?.let { MetadataRow(stringResource(R.string.meta_creator), it) }+            androidx.compose.foundation.layout.Column(Modifier.verticalScroll(rememberScrollState())) {+                TextField(value = title, onValueChange = { title = it }, label = { Text(stringResource(R.string.meta_title)) }, singleLine = true, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(6.dp))+                TextField(value = author, onValueChange = { author = it }, label = { Text(stringResource(R.string.meta_author)) }, singleLine = true, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(6.dp))+                TextField(value = subject, onValueChange = { subject = it }, label = { Text(stringResource(R.string.meta_subject)) }, singleLine = true, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(6.dp))+                TextField(value = description, onValueChange = { description = it }, label = { Text(stringResource(R.string.meta_description)) }, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(6.dp))+                TextField(value = keywords, onValueChange = { keywords = it }, label = { Text(stringResource(R.string.meta_keywords)) }, singleLine = true, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(8.dp))                 metadata.creationDate?.let { MetadataRow(stringResource(R.string.meta_created), it) }                 metadata.modifiedDate?.let { MetadataRow(stringResource(R.string.meta_modified), it) }-                metadata.subject?.let { MetadataRow(stringResource(R.string.meta_subject), it) }-                metadata.description?.let { MetadataRow(stringResource(R.string.meta_description), it) }-                if (metadata.keywords.isNotEmpty()) MetadataRow(stringResource(R.string.meta_keywords), metadata.keywords.joinToString(", "))                 metadata.pageCount?.let { MetadataRow(stringResource(R.string.meta_pages), it.toString()) }                 metadata.wordCount?.let { MetadataRow(stringResource(R.string.meta_words), it.toString()) }                 metadata.fileSize?.let { MetadataRow("File Size", formatFileSize(it)) }-                if (listOfNotNull(metadata.title, metadata.author, metadata.creator, metadata.creationDate, metadata.modifiedDate, metadata.subject, metadata.description, metadata.pageCount, metadata.wordCount, metadata.fileSize).isEmpty() && metadata.keywords.isEmpty())-                    Text(stringResource(R.string.meta_none), style = MaterialTheme.typography.bodyMedium)             }         },-        confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } })+        confirmButton = {+            TextButton(onClick = {+                onSave(metadata.copy(+                    title = title.ifBlank { null },+                    author = author.ifBlank { null },+                    subject = subject.ifBlank { null },+                    description = description.ifBlank { null },+                    keywords = keywords.split(",").map { it.trim() }.filter { it.isNotEmpty() }+                ))+                onDismiss()+            }) { Text(stringResource(R.string.save)) }+        },+        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }) }  @Composable private fun MetadataRow(label: String, value: String) {@@ -589,6 +691,7 @@ private fun documentToHtml(document: OdfDocument): String {                 is OdfContentBlock.Table -> { sb.append("<table>"); for (row in block.table.rows) { sb.append("<tr>"); for (cell in row.cells) { if (cell.isCovered) continue; sb.append("<td"); if (cell.colSpan > 1) sb.append(""" colspan="${cell.colSpan}""""); if (cell.rowSpan > 1) sb.append(""" rowspan="${cell.rowSpan}""""); sb.append(">"); for (para in cell.paragraphs) for (span in para.spans) sb.append(span.text.replace("&", "&amp;").replace("<", "&lt;")); sb.append("</td>") }; sb.append("</tr>") }; sb.append("</table>") }                 is OdfContentBlock.Image -> sb.append("<p>[Image]</p>")                 is OdfContentBlock.Chart -> sb.append("<p>[Chart]</p>")+                is OdfContentBlock.Formula -> sb.append("<p><i>${OdfMath.parse(block.mathml)?.let { OdfMath.toText(it) }.orEmpty().replace("&", "&amp;").replace("<", "&lt;")}</i></p>")                 is OdfContentBlock.PageBreak -> sb.append("""<hr style="page-break-after:always">""")             }         }
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 ca8e9c37fb..ab32b2dccd 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfDocument.kt@@ -45,10 +45,11 @@ sealed class OdfContentBlock {     data class Table(val table: OdfTable) : OdfContentBlock()     data class Image(val image: OdfImage) : OdfContentBlock()     data class Chart(val chart: OdfChart) : OdfContentBlock()+    data class Formula(val mathml: String) : OdfContentBlock()     data object PageBreak : OdfContentBlock() } -enum class ChartType { BAR, LINE, PIE, AREA }+enum class ChartType { BAR, LINE, PIE, AREA, DONUT, SCATTER, STACKED_BAR }  data class OdfChartSeries(val name: String, val values: List<Float>) @@ -71,13 +72,61 @@ data class OdfParagraph(     val listLevel: Int = 0,     val listType: ListType = ListType.BULLET,     val listItemIndex: Int = 0,-    val direction: LayoutDirection? = null+    val direction: LayoutDirection? = null,+    // Line spacing as a multiple of normal (1.0 = single, 1.5 = 150%); null = unspecified. (A6)+    val lineHeightPercent: Float? = null,+    // Paragraph border color (single uniform border) if any. (A7)+    val borderColor: Long? = null,+    // Number format for numbered lists: "1", "a", "A", "i", "I". (F42)+    val listNumberFormat: String = "1",+    // Bullet glyph for bullet lists. (F42)+    val listBulletChar: String = "\u2022",+    // Number prefix/suffix (e.g. "(" and ")" for "(1)"). (F42)+    val listNumberPrefix: String = "",+    val listNumberSuffix: String = ".",+    // Tab stop positions in px (96dpi). (A4)+    val tabStops: List<Float> = emptyList() )  enum class ParagraphStyle { HEADING1, HEADING2, HEADING3, HEADING4, BODY, LIST_ITEM, TABLE_HEADER }  enum class ListType { BULLET, NUMBERED } +/** Formats a 1-based list item index using an ODF number-format token ("1","a","A","i","I"). (F42) */+fun formatListNumber(index: Int, format: String): String {+    val n = index.coerceAtLeast(1)+    return when (format) {+        "a" -> toAlpha(n).lowercase()+        "A" -> toAlpha(n)+        "i" -> toRoman(n).lowercase()+        "I" -> toRoman(n)+        else -> n.toString()+    }+}++private fun toAlpha(n: Int): String {+    val sb = StringBuilder()+    var v = n+    while (v > 0) {+        val rem = (v - 1) % 26+        sb.insert(0, ('A' + rem))+        v = (v - 1) / 26+    }+    return sb.toString()+}++private fun toRoman(n: Int): String {+    if (n !in 1..3999) return n.toString()+    val values = intArrayOf(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)+    val symbols = arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")+    val sb = StringBuilder()+    var v = n+    for (i in values.indices) {+        while (v >= values[i]) { sb.append(symbols[i]); v -= values[i] }+    }+    return sb.toString()+}+ data class OdfSpan(     val text: String,     val bold: Boolean = false,@@ -100,7 +149,9 @@ data class OdfImage(     val imageData: ByteArray,     val width: Float = 0f,     val height: Float = 0f,-    val anchorType: String = ""+    val anchorType: String = "",+    // Rotation in degrees clockwise (E38).+    val rotationDegrees: Float = 0f )  data class OdfTable(@@ -140,7 +191,26 @@ data class OdfCell(     val italic: Boolean = false,     val alignment: TextAlign? = null,     val borderColor: Long? = null,-    val isCovered: Boolean = false+    val isCovered: Boolean = false,+    // OpenFormula source (e.g. "of:=SUM([.A1:.A3])"), if this is a formula cell. (H49)+    val formula: String? = null,+    // ODF value type: "float", "string", "date", "percentage", "currency", "boolean". (H50/H54)+    val valueType: String? = null,+    // Cached numeric value from office:value, if numeric. (H54)+    val numberValue: Double? = null,+    // Resolved number/date/currency display format. (H50)+    val numberFormat: OdfNumberFormat? = null,+    // Wrap text in cell. (H53)+    val wrap: Boolean = false+)++/** Resolved spreadsheet number-format descriptor (H50). */+data class OdfNumberFormat(+    val decimals: Int? = null,+    val percent: Boolean = false,+    val currencySymbol: String? = null,+    val grouping: Boolean = false,+    val isDate: Boolean = false )  data class OdfSlide(
office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.ktnew file mode 100644index 0000000000..03a3d0bdbc--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfFormulaEngine.kt@@ -0,0 +1,298 @@+package com.vayunmathur.office.odf++import kotlin.math.abs+import kotlin.math.pow+import kotlin.math.roundToLong+import kotlin.math.sqrt++/**+ * Minimal OpenFormula evaluator for spreadsheet cells (H49).+ *+ * Supports: numeric literals, cell references ([.A1]) and ranges ([.A1:.B3]),+ * arithmetic (+ - * / ^), comparisons (= <> < <= > >=), parentheses, and the+ * functions SUM, AVERAGE, MIN, MAX, COUNT, COUNTA, IF, ABS, ROUND, SQRT,+ * POWER, MOD, AND, OR, NOT. References resolve against the sheet grid and+ * recursively evaluate dependent formula cells (with cycle protection).+ *+ * This is a best-effort engine: it covers common cases, not the full+ * OpenFormula spec. Cells whose formula cannot be evaluated fall back to their+ * cached text value.+ */+object OdfFormulaEngine {++    /** Display string for a cell: evaluates the formula if present, else cached text. */+    fun displayValue(sheet: OdfSheet, row: Int, col: Int): String {+        val cell = sheet.rows.getOrNull(row)?.cells?.getOrNull(col) ?: return ""+        if (cell.formula == null) return cell.text+        return try {+            val v = Evaluator(sheet, mutableSetOf()).evaluateCell(row, col)+            if (v.isNaN()) cell.text.ifEmpty { "#ERR" } else formatWithStyle(v, cell.numberFormat)+        } catch (_: Exception) {+            cell.text+        }+    }++    /** Formats a numeric value using an ODF number-format descriptor (H50). */+    fun formatWithStyle(v: Double, fmt: OdfNumberFormat?): String {+        if (fmt == null) return formatNumber(v)+        var value = v+        if (fmt.percent) value *= 100.0+        val decimals = (fmt.decimals ?: 2).coerceIn(0, 10)+        val pattern = (if (fmt.grouping) "%,." else "%.") + decimals + "f"+        var s = String.format(pattern, value)+        if (fmt.percent) s += "%"+        if (fmt.currencySymbol != null) s = fmt.currencySymbol + s+        return s+    }++    /** True when the (evaluated) cell holds a numeric value (used for right-alignment, H54). */+    fun isNumeric(sheet: OdfSheet, row: Int, col: Int): Boolean {+        val cell = sheet.rows.getOrNull(row)?.cells?.getOrNull(col) ?: return false+        if (cell.numberValue != null) return true+        if (cell.valueType in setOf("float", "percentage", "currency")) return true+        if (cell.formula != null) {+            return try { !Evaluator(sheet, mutableSetOf()).evaluateCell(row, col).isNaN() } catch (_: Exception) { false }+        }+        return cell.text.toDoubleOrNull() != null+    }++    fun formatNumber(v: Double): String {+        if (v.isNaN()) return "#ERR"+        if (v.isInfinite()) return "#DIV/0!"+        return if (v == v.toLong().toDouble()) v.toLong().toString() else "%.4f".format(v).trimEnd('0').trimEnd('.')+    }++    private fun colToIndex(col: String): Int {+        var n = 0+        for (c in col) { if (c.isLetter()) n = n * 26 + (c.uppercaseChar() - 'A' + 1) }+        return n - 1+    }++    private class Evaluator(val sheet: OdfSheet, val visiting: MutableSet<Long>) {++        fun evaluateCell(row: Int, col: Int): Double {+            val key = row * 1_000_000L + col+            if (key in visiting) return Double.NaN // cycle+            val cell = sheet.rows.getOrNull(row)?.cells?.getOrNull(col) ?: return 0.0+            if (cell.formula == null) {+                return cell.numberValue ?: cell.text.toDoubleOrNull() ?: 0.0+            }+            visiting.add(key)+            try {+                val expr = normalize(cell.formula)+                return Parser(expr).parseExpression()+            } finally {+                visiting.remove(key)+            }+        }++        private fun normalize(formula: String): String {+            var f = formula.trim()+            if (f.startsWith("of:")) f = f.substring(3)+            if (f.startsWith("=")) f = f.substring(1)+            return f+        }++        // Recursive-descent parser over the formula string.+        private inner class Parser(val s: String) {+            var pos = 0++            fun parseExpression(): Double = parseComparison()++            private fun parseComparison(): Double {+                var left = parseAddSub()+                while (true) {+                    skipWs()+                    val op = when {+                        match("<=") -> "<="; match(">=") -> ">="; match("<>") -> "<>"+                        peek() == '<' -> { pos++; "<" }+                        peek() == '>' -> { pos++; ">" }+                        peek() == '=' -> { pos++; "=" }+                        else -> return left+                    }+                    val right = parseAddSub()+                    val b = when (op) {+                        "<" -> left < right; "<=" -> left <= right; ">" -> left > right+                        ">=" -> left >= right; "=" -> left == right; "<>" -> left != right+                        else -> false+                    }+                    left = if (b) 1.0 else 0.0+                }+            }++            private fun parseAddSub(): Double {+                var v = parseMulDiv()+                while (true) {+                    skipWs()+                    when (peek()) {+                        '+' -> { pos++; v += parseMulDiv() }+                        '-' -> { pos++; v -= parseMulDiv() }+                        else -> return v+                    }+                }+            }++            private fun parseMulDiv(): Double {+                var v = parsePower()+                while (true) {+                    skipWs()+                    when (peek()) {+                        '*' -> { pos++; v *= parsePower() }+                        '/' -> { pos++; v /= parsePower() }+                        else -> return v+                    }+                }+            }++            private fun parsePower(): Double {+                val base = parseUnary()+                skipWs()+                if (peek() == '^') { pos++; return base.pow(parseUnary()) }+                return base+            }++            private fun parseUnary(): Double {+                skipWs()+                if (peek() == '-') { pos++; return -parseUnary() }+                if (peek() == '+') { pos++; return parseUnary() }+                return parsePrimary()+            }++            private fun parsePrimary(): Double {+                skipWs()+                val c = peek()+                when {+                    c == '(' -> { pos++; val v = parseExpression(); skipWs(); if (peek() == ')') pos++; return v }+                    c == '[' -> { val list = parseReference(); return list.firstOrNull() ?: 0.0 }+                    c == '"' -> { parseString(); return Double.NaN } // strings -> NaN numerically+                    c.isDigit() || c == '.' -> return parseNumber()+                    c.isLetter() -> return parseFunctionOrConst()+                    else -> { pos++; return 0.0 }+                }+            }++            private fun parseNumber(): Double {+                val start = pos+                while (pos < s.length && (s[pos].isDigit() || s[pos] == '.' || s[pos] == 'E' || s[pos] == 'e')) pos+++                return s.substring(start, pos).toDoubleOrNull() ?: 0.0+            }++            private fun parseString(): String {+                pos++ // opening quote+                val sb = StringBuilder()+                while (pos < s.length && s[pos] != '"') { sb.append(s[pos]); pos++ }+                if (pos < s.length) pos++ // closing quote+                return sb.toString()+            }++            /** Parses a [.A1] reference or [.A1:.B3] range into a list of numeric values. */+            private fun parseReference(): List<Double> {+                pos++ // '['+                val sb = StringBuilder()+                while (pos < s.length && s[pos] != ']') { sb.append(s[pos]); pos++ }+                if (pos < s.length) pos++ // ']'+                val inner = sb.toString().replace("$", "").replace(".", "")+                return if (inner.contains(":")) {+                    val (a, b) = inner.split(":", limit = 2)+                    expandRange(a, b)+                } else {+                    listOf(cellValue(inner))+                }+            }++            private fun parseCellArg(): List<Double> {+                skipWs()+                return if (peek() == '[') parseReference() else listOf(parseExpression())+            }++            private fun parseFunctionOrConst(): Double {+                val start = pos+                while (pos < s.length && (s[pos].isLetterOrDigit() || s[pos] == '_' || s[pos] == '.')) pos+++                var name = s.substring(start, pos).uppercase()+                if (name.startsWith("ORG.OPENOFFICE.")) name = name.removePrefix("ORG.OPENOFFICE.")+                skipWs()+                if (peek() != '(') {+                    return when (name) { "TRUE" -> 1.0; "FALSE" -> 0.0; "PI" -> Math.PI; else -> Double.NaN }+                }+                pos++ // '('+                val args = mutableListOf<List<Double>>()+                skipWs()+                if (peek() != ')') {+                    args.add(parseCellArg())+                    skipWs()+                    while (peek() == ';' || peek() == ',') { pos++; args.add(parseCellArg()); skipWs() }+                }+                if (peek() == ')') pos+++                return applyFunction(name, args)+            }++            private fun applyFunction(name: String, args: List<List<Double>>): Double {+                val flat = args.flatten()+                val nums = flat.filter { !it.isNaN() }+                return when (name) {+                    "SUM" -> nums.sum()+                    "AVERAGE" -> if (nums.isEmpty()) Double.NaN else nums.average()+                    "MIN" -> nums.minOrNull() ?: Double.NaN+                    "MAX" -> nums.maxOrNull() ?: Double.NaN+                    "COUNT" -> nums.size.toDouble()+                    "COUNTA" -> flat.size.toDouble()+                    "ABS" -> abs(flat.firstOrNull() ?: 0.0)+                    "SQRT" -> sqrt(flat.firstOrNull() ?: 0.0)+                    "ROUND" -> {+                        val v = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val d = (args.getOrNull(1)?.firstOrNull() ?: 0.0).toInt()+                        val factor = 10.0.pow(d)+                        (v * factor).roundToLong() / factor+                    }+                    "POWER" -> (args.getOrNull(0)?.firstOrNull() ?: 0.0).pow(args.getOrNull(1)?.firstOrNull() ?: 0.0)+                    "MOD" -> {+                        val a = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        val b = args.getOrNull(1)?.firstOrNull() ?: 1.0+                        if (b == 0.0) Double.NaN else a % b+                    }+                    "IF" -> {+                        val cond = args.getOrNull(0)?.firstOrNull() ?: 0.0+                        if (cond != 0.0 && !cond.isNaN()) args.getOrNull(1)?.firstOrNull() ?: 0.0+                        else args.getOrNull(2)?.firstOrNull() ?: 0.0+                    }+                    "AND" -> if (nums.isNotEmpty() && nums.all { it != 0.0 }) 1.0 else 0.0+                    "OR" -> if (nums.any { it != 0.0 }) 1.0 else 0.0+                    "NOT" -> if ((flat.firstOrNull() ?: 0.0) == 0.0) 1.0 else 0.0+                    else -> Double.NaN+                }+            }++            private fun cellValue(ref: String): Double {+                val m = Regex("([A-Za-z]+)(\\d+)").find(ref) ?: return 0.0+                val col = colToIndex(m.groupValues[1])+                val row = (m.groupValues[2].toIntOrNull() ?: 1) - 1+                return evaluateCell(row, col)+            }++            private fun expandRange(a: String, b: String): List<Double> {+                val ma = Regex("([A-Za-z]+)(\\d+)").find(a) ?: return emptyList()+                val mb = Regex("([A-Za-z]+)(\\d+)").find(b) ?: return emptyList()+                val c1 = colToIndex(ma.groupValues[1]); val r1 = (ma.groupValues[2].toIntOrNull() ?: 1) - 1+                val c2 = colToIndex(mb.groupValues[1]); val r2 = (mb.groupValues[2].toIntOrNull() ?: 1) - 1+                val out = mutableListOf<Double>()+                for (r in minOf(r1, r2)..maxOf(r1, r2)) {+                    for (c in minOf(c1, c2)..maxOf(c1, c2)) {+                        val cell = sheet.rows.getOrNull(r)?.cells?.getOrNull(c)+                        if (cell != null && !cell.isCovered && (cell.text.isNotEmpty() || cell.formula != null || cell.numberValue != null)) {+                            out.add(evaluateCell(r, c))+                        }+                    }+                }+                return out+            }++            private fun peek(): Char = if (pos < s.length) s[pos] else '\u0000'+            private fun skipWs() { while (pos < s.length && s[pos].isWhitespace()) pos++ }+            private fun match(token: String): Boolean {+                skipWs()+                if (s.startsWith(token, pos)) { pos += token.length; return true }+                return false+            }+        }+    }+}
office/src/main/java/com/vayunmathur/office/odf/OdfMath.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfMath.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfMath.ktnew file mode 100644index 0000000000..ac8d66d812--- /dev/null+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfMath.kt@@ -0,0 +1,143 @@+package com.vayunmathur.office.odf++import com.vayunmathur.office.odf.MathNode.Fenced+import com.vayunmathur.office.odf.MathNode.Frac+import com.vayunmathur.office.odf.MathNode.Root+import com.vayunmathur.office.odf.MathNode.Row+import com.vayunmathur.office.odf.MathNode.Sqrt+import com.vayunmathur.office.odf.MathNode.Sub+import com.vayunmathur.office.odf.MathNode.SubSup+import com.vayunmathur.office.odf.MathNode.Sup+import com.vayunmathur.office.odf.MathNode.Token+import org.xmlpull.v1.XmlPullParser+import org.xmlpull.v1.XmlPullParserFactory++/** Parsed MathML presentation tree for layout rendering (D34). */+sealed class MathNode {+    data class Row(val children: List<MathNode>) : MathNode()+    data class Token(val text: String, val isOperator: Boolean = false) : MathNode()+    data class Frac(val numerator: MathNode, val denominator: MathNode) : MathNode()+    data class Sup(val base: MathNode, val exponent: MathNode) : MathNode()+    data class Sub(val base: MathNode, val subscript: MathNode) : MathNode()+    data class SubSup(val base: MathNode, val subscript: MathNode, val superscript: MathNode) : MathNode()+    data class Sqrt(val radicand: MathNode) : MathNode()+    data class Root(val radicand: MathNode, val index: MathNode) : MathNode()+    data class Fenced(val open: String, val close: String, val body: MathNode) : MathNode()+}++object OdfMath {++    /** Parses an embedded math object's content.xml (MathML). Returns null if unparseable. */+    fun parse(xml: String): MathNode? {+        return try {+            val factory = XmlPullParserFactory.newInstance()+            factory.isNamespaceAware = true+            val parser = factory.newPullParser()+            parser.setInput(xml.reader())+            var event = parser.eventType+            while (event != XmlPullParser.END_DOCUMENT) {+                if (event == XmlPullParser.START_TAG && parser.name == "math") {+                    return Row(parseChildren(parser, "math"))+                }+                event = parser.next()+            }+            null+        } catch (_: Exception) { null }+    }++    private fun attr(parser: XmlPullParser, name: String): String? {+        for (i in 0 until parser.attributeCount) if (parser.getAttributeName(i) == name) return parser.getAttributeValue(i)+        return null+    }++    /** Parses all child element nodes until the matching end tag of [endTag] at the current depth. */+    private fun parseChildren(parser: XmlPullParser, endTag: String): List<MathNode> {+        val nodes = mutableListOf<MathNode>()+        val depth = parser.depth+        var event = parser.next()+        while (!(event == XmlPullParser.END_TAG && parser.depth == depth && parser.name == endTag)) {+            if (event == XmlPullParser.START_TAG) parseElement(parser)?.let { nodes.add(it) }+            if (event == XmlPullParser.END_DOCUMENT) break+            event = parser.next()+        }+        return nodes+    }++    /** Parses a single element (assumes parser positioned at its START_TAG). Consumes through its END_TAG. */+    private fun parseElement(parser: XmlPullParser): MathNode? {+        return when (parser.name) {+            "mi", "mn", "mo", "mtext", "ms" -> {+                val isOp = parser.name == "mo"+                Token(readText(parser, parser.name), isOp)+            }+            "mspace" -> { skip(parser); Token(" ") }+            "mrow", "mstyle", "mpadded", "merror", "math" -> {+                val tag = parser.name+                Row(parseChildren(parser, tag))+            }+            "mfrac" -> {+                val kids = parseChildren(parser, "mfrac")+                Frac(kids.getOrElse(0) { Row(emptyList()) }, kids.getOrElse(1) { Row(emptyList()) })+            }+            "msup" -> {+                val kids = parseChildren(parser, "msup")+                Sup(kids.getOrElse(0) { Row(emptyList()) }, kids.getOrElse(1) { Row(emptyList()) })+            }+            "msub" -> {+                val kids = parseChildren(parser, "msub")+                Sub(kids.getOrElse(0) { Row(emptyList()) }, kids.getOrElse(1) { Row(emptyList()) })+            }+            "msubsup" -> {+                val kids = parseChildren(parser, "msubsup")+                SubSup(kids.getOrElse(0) { Row(emptyList()) }, kids.getOrElse(1) { Row(emptyList()) }, kids.getOrElse(2) { Row(emptyList()) })+            }+            "msqrt" -> Sqrt(Row(parseChildren(parser, "msqrt")))+            "mroot" -> {+                val kids = parseChildren(parser, "mroot")+                Root(kids.getOrElse(0) { Row(emptyList()) }, kids.getOrElse(1) { Token("") })+            }+            "mfenced" -> {+                val open = attr(parser, "open") ?: "("+                val close = attr(parser, "close") ?: ")"+                Fenced(open, close, Row(parseChildren(parser, "mfenced")))+            }+            "semantics" -> Row(parseChildren(parser, "semantics"))+            "annotation", "annotation-xml" -> { skip(parser); null }+            else -> { val tag = parser.name; Row(parseChildren(parser, tag)) }+        }+    }++    private fun readText(parser: XmlPullParser, endTag: String): String {+        val sb = StringBuilder()+        val depth = parser.depth+        var event = parser.next()+        while (!(event == XmlPullParser.END_TAG && parser.depth == depth && parser.name == endTag)) {+            if (event == XmlPullParser.TEXT) sb.append(parser.text)+            if (event == XmlPullParser.END_DOCUMENT) break+            event = parser.next()+        }+        return sb.toString().trim()+    }++    private fun skip(parser: XmlPullParser) {+        val depth = parser.depth+        var event = parser.next()+        while (!(event == XmlPullParser.END_TAG && parser.depth == depth)) {+            if (event == XmlPullParser.END_DOCUMENT) break+            event = parser.next()+        }+    }++    /** Flattens a node to plain text (fallback when layout isn't desired). */+    fun toText(node: MathNode): String = when (node) {+        is MathNode.Row -> node.children.joinToString("") { toText(it) }+        is MathNode.Token -> node.text+        is MathNode.Frac -> "(${toText(node.numerator)})/(${toText(node.denominator)})"+        is MathNode.Sup -> "${toText(node.base)}^${toText(node.exponent)}"+        is MathNode.Sub -> "${toText(node.base)}_${toText(node.subscript)}"+        is MathNode.SubSup -> "${toText(node.base)}_${toText(node.subscript)}^${toText(node.superscript)}"+        is MathNode.Sqrt -> "\u221A(${toText(node.radicand)})"+        is MathNode.Root -> "root[${toText(node.index)}](${toText(node.radicand)})"+        is MathNode.Fenced -> "${node.open}${toText(node.body)}${node.close}"+    }+}
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 93780b4d14..39e49c00b2 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfParser.kt@@ -13,6 +13,12 @@ object OdfParser {      fun parse(context: Context, uri: Uri, fileName: String): OdfDocument {         val entries = extractAllEntries(context, uri)+        // Encrypted ODF detection (J67): manifest declares per-file encryption-data.+        entries.textEntries["META-INF/manifest.xml"]?.let { manifest ->+            if (manifest.contains("manifest:encryption-data") || manifest.contains("encryption-data")) {+                throw IllegalArgumentException("This document is password-protected (encrypted ODF), which is not supported.")+            }+        }         val contentXml = entries.textEntries["content.xml"]             ?: throw IllegalArgumentException("Not a valid ODF file: missing content.xml")         val stylesXml = entries.textEntries["styles.xml"]@@ -22,10 +28,14 @@ object OdfParser {         stylesXml?.let { styleMap.putAll(parseStyles(it)) }         styleMap.putAll(parseStyles(contentXml)) -        val listStyleMap = mutableMapOf<String, ListType>()+        val listStyleMap = mutableMapOf<String, ListStyleInfo>()         stylesXml?.let { listStyleMap.putAll(parseListStyles(it)) }         listStyleMap.putAll(parseListStyles(contentXml)) +        val numberStyleMap = mutableMapOf<String, OdfNumberFormat>()+        stylesXml?.let { numberStyleMap.putAll(parseNumberStyles(it)) }+        numberStyleMap.putAll(parseNumberStyles(contentXml))+         var metadata = metaXml?.let { parseMetadata(it) } ?: OdfMetadata()          // File size@@ -44,7 +54,7 @@ object OdfParser {         val type = detectType(contentXml)         return when (type) {             DocType.TEXT -> parseTextDocument(contentXml, styleMap, listStyleMap, fileName, metadata, images, headerFooter, objectContents)-            DocType.SPREADSHEET -> parseSpreadsheet(contentXml, styleMap, fileName, metadata, images)+            DocType.SPREADSHEET -> parseSpreadsheet(contentXml, styleMap, numberStyleMap, fileName, metadata, images)             DocType.PRESENTATION -> parsePresentation(contentXml, styleMap, fileName, metadata, images)             DocType.DRAWING -> parseDrawing(contentXml, styleMap, fileName, metadata, images)         }@@ -60,20 +70,34 @@ object OdfParser {     private fun extractAllEntries(context: Context, uri: Uri): ZipEntries {         val textEntries = mutableMapOf<String, String>()         val binaryEntries = mutableMapOf<String, ByteArray>()-        val textFiles = setOf("content.xml", "styles.xml", "meta.xml")--        context.contentResolver.openInputStream(uri)?.use { inputStream ->-            ZipInputStream(inputStream).use { zip ->-                var entry = zip.nextEntry-                while (entry != null) {-                    val name = entry.name-                    when {-                        name in textFiles -> textEntries[name] = zip.bufferedReader().readText()-                        name.startsWith("Object") && name.endsWith("content.xml") -> textEntries[name] = zip.bufferedReader().readText()-                        name.startsWith("Pictures/") && !entry.isDirectory -> binaryEntries[name] = zip.readBytes()-                    }-                    entry = zip.nextEntry+        val textFiles = setOf("content.xml", "styles.xml", "meta.xml", "META-INF/manifest.xml")++        val raw = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0)+        // Flat ODF (.fodt/.fods/.fodp) is a single XML file, not a zip. (J70)+        val isZip = raw.size >= 2 && raw[0] == 'P'.code.toByte() && raw[1] == 'K'.code.toByte()+        if (!isZip) {+            val xml = String(raw, Charsets.UTF_8)+            if (xml.contains("office:document")) {+                textEntries["content.xml"] = xml+                textEntries["styles.xml"] = xml+                textEntries["meta.xml"] = xml+            }+            return ZipEntries(textEntries, binaryEntries)+        }++        ZipInputStream(raw.inputStream()).use { zip ->+            var entry = zip.nextEntry+            while (entry != null) {+                val name = entry.name+                when {+                    name in textFiles -> textEntries[name] = zip.bufferedReader().readText()+                    name.startsWith("Object") && name.endsWith("content.xml") -> textEntries[name] = zip.bufferedReader().readText()+                    !entry.isDirectory && (+                        name.startsWith("Pictures/") || name.startsWith("media/") ||+                        name.startsWith("ObjectReplacements") || name.startsWith("Thumbnails/")+                        ) -> binaryEntries[name] = zip.readBytes()                 }+                entry = zip.nextEntry             }         }         return ZipEntries(textEntries, binaryEntries)@@ -137,6 +161,14 @@ object OdfParser {         } catch (_: Exception) { null }     } +    /** Converts an ODF draw:transform rotate(theta) into degrees clockwise for Compose (E38). */+    private fun parseRotationDegrees(transform: String?): Float {+        if (transform == null) return 0f+        val m = Regex("rotate\\(([-0-9.]+)\\)").find(transform) ?: return 0f+        val rad = m.groupValues[1].toFloatOrNull() ?: return 0f+        return -(rad * 180.0 / Math.PI).toFloat()+    }+     // --- Style parsing ---      private data class StyleInfo(@@ -165,7 +197,12 @@ object OdfParser {         val cellBackgroundColor: Long? = null,         val cellBorderColor: Long? = null,         val writingMode: String? = null,-        val columnWidth: Float? = null+        val columnWidth: Float? = null,+        val lineHeightPercent: Float? = null,+        val paragraphBorderColor: Long? = null,+        val tabStops: List<Float> = emptyList(),+        val dataStyleName: String? = null,+        val cellWrap: Boolean = false     )      private fun parseStyles(xml: String): Map<String, StyleInfo> {@@ -176,8 +213,9 @@ object OdfParser {             if (eventType == XmlPullParser.START_TAG && parser.name == "style" && parser.namespace?.contains("style") == true) {                 val styleName = getAttr(parser, "name")                 val parentStyle = getAttr(parser, "parent-style-name")+                val dataStyle = getAttr(parser, "data-style-name")                 if (styleName != null) {-                    styles[styleName] = parseStyleProperties(parser, parentStyle)+                    styles[styleName] = parseStyleProperties(parser, parentStyle).copy(dataStyleName = dataStyle)                 }             }             eventType = parser.next()@@ -196,8 +234,12 @@ object OdfParser {         var breakBefore: String? = null; var breakAfter: String? = null         var drawFillColor: Long? = null; var drawStrokeColor: Long? = null; var drawStrokeWidth: Float? = null         var cellBgColor: Long? = null; var cellBorderColor: Long? = null+        var cellWrap = false         var writingMode: String? = null         var columnWidth: Float? = null+        var lineHeightPercent: Float? = null+        var paraBorderColor: Long? = null+        val tabStops = mutableListOf<Float>()          val depth = parser.depth         var eventType = parser.next()@@ -237,6 +279,15 @@ object OdfParser {                         breakBefore = getAttr(parser, "break-before")                         breakAfter = getAttr(parser, "break-after")                         getAttr(parser, "writing-mode")?.let { writingMode = it }+                        getAttr(parser, "line-height")?.let { lh ->+                            if (lh.endsWith("%")) lh.dropLast(1).toFloatOrNull()?.let { lineHeightPercent = it / 100f }+                        }+                        getAttr(parser, "border")?.let { b ->+                            b.split(" ").lastOrNull { it.startsWith("#") }?.let { paraBorderColor = parseColor(it) }+                        }+                    }+                    "tab-stop" -> {+                        getAttr(parser, "position")?.let { tabStops.add(parseDimension(it)) }                     }                     "drawing-page-properties" -> {                         if (getAttr(parser, "fill") == "solid") {@@ -255,6 +306,7 @@ object OdfParser {                         getAttr(parser, "border")?.let { border ->                             border.split(" ").lastOrNull { it.startsWith("#") }?.let { cellBorderColor = parseColor(it) }                         }+                        if (getAttr(parser, "wrap-option") == "wrap") cellWrap = true                     }                     "table-column-properties" -> {                         getAttr(parser, "column-width")?.let { columnWidth = parseDimension(it) }@@ -268,7 +320,8 @@ object OdfParser {             underline, strikethrough, color, bgColor, superscript, subscript,             textAlign, marginLeft, marginTop, marginBottom, textIndent, paraBgColor,             breakBefore, breakAfter, drawFillColor, drawStrokeColor, drawStrokeWidth,-            cellBgColor, cellBorderColor, writingMode, columnWidth+            cellBgColor, cellBorderColor, writingMode, columnWidth,+            lineHeightPercent, paraBorderColor, tabStops, null, cellWrap         )     } @@ -303,7 +356,12 @@ object OdfParser {                 cellBackgroundColor = info.cellBackgroundColor ?: parent.cellBackgroundColor,                 cellBorderColor = info.cellBorderColor ?: parent.cellBorderColor,                 writingMode = info.writingMode ?: parent.writingMode,-                columnWidth = info.columnWidth ?: parent.columnWidth+                columnWidth = info.columnWidth ?: parent.columnWidth,+                lineHeightPercent = info.lineHeightPercent ?: parent.lineHeightPercent,+                paragraphBorderColor = info.paragraphBorderColor ?: parent.paragraphBorderColor,+                tabStops = if (info.tabStops.isNotEmpty()) info.tabStops else parent.tabStops,+                dataStyleName = info.dataStyleName ?: parent.dataStyleName,+                cellWrap = info.cellWrap || parent.cellWrap             )         }         return info@@ -311,21 +369,58 @@ object OdfParser {      // --- List style parsing --- -    private fun parseListStyles(xml: String): Map<String, ListType> {-        val map = mutableMapOf<String, ListType>()+    data class ListLevelStyle(+        val numbered: Boolean,+        val numberFormat: String = "1",+        val bulletChar: String = "\u2022",+        val prefix: String = "",+        val suffix: String = ".",+        val startValue: Int = 1+    )++    data class ListStyleInfo(val levels: Map<Int, ListLevelStyle>) {+        fun levelStyle(level: Int): ListLevelStyle {+            if (levels.isEmpty()) return ListLevelStyle(numbered = false)+            return levels[level] ?: levels[levels.keys.minByOrNull { kotlin.math.abs(it - level) }] ?: ListLevelStyle(numbered = false)+        }+        val anyNumbered: Boolean get() = levels.values.any { it.numbered }+    }++    private fun parseListStyles(xml: String): Map<String, ListStyleInfo> {+        val map = mutableMapOf<String, ListStyleInfo>()         val parser = newParser(xml)         var eventType = parser.eventType         var currentName: String? = null-        var foundNumbered = false+        var levels = mutableMapOf<Int, ListLevelStyle>()          while (eventType != XmlPullParser.END_DOCUMENT) {             when (eventType) {                 XmlPullParser.START_TAG -> when (parser.name) {-                    "list-style" -> { currentName = getAttr(parser, "name"); foundNumbered = false }-                    "list-level-style-number" -> foundNumbered = true+                    "list-style" -> { currentName = getAttr(parser, "name"); levels = mutableMapOf() }+                    "list-level-style-number" -> {+                        val lvl = getAttr(parser, "level")?.toIntOrNull() ?: 1+                        levels[lvl] = ListLevelStyle(+                            numbered = true,+                            numberFormat = getAttr(parser, "num-format")?.ifEmpty { "1" } ?: "1",+                            prefix = getAttr(parser, "num-prefix") ?: "",+                            suffix = getAttr(parser, "num-suffix") ?: ".",+                            startValue = getAttr(parser, "start-value")?.toIntOrNull() ?: 1+                        )+                    }+                    "list-level-style-bullet" -> {+                        val lvl = getAttr(parser, "level")?.toIntOrNull() ?: 1+                        levels[lvl] = ListLevelStyle(+                            numbered = false,+                            bulletChar = getAttr(parser, "bullet-char")?.ifEmpty { "\u2022" } ?: "\u2022"+                        )+                    }+                    "list-level-style-image" -> {+                        val lvl = getAttr(parser, "level")?.toIntOrNull() ?: 1+                        levels[lvl] = ListLevelStyle(numbered = false, bulletChar = "\u25AA")+                    }                 }                 XmlPullParser.END_TAG -> if (parser.name == "list-style" && currentName != null) {-                    map[currentName] = if (foundNumbered) ListType.NUMBERED else ListType.BULLET+                    map[currentName] = ListStyleInfo(levels.toMap())                     currentName = null                 }             }@@ -334,6 +429,51 @@ object OdfParser {         return map     } +    // --- Number format (data style) parsing (H50) ---++    private fun parseNumberStyles(xml: String): Map<String, OdfNumberFormat> {+        val map = mutableMapOf<String, OdfNumberFormat>()+        val parser = newParser(xml)+        var e = parser.eventType+        var curName: String? = null+        var type = ""+        var decimals: Int? = null+        var currency: String? = null+        var grouping = false+        fun flush() {+            val n = curName ?: return+            map[n] = OdfNumberFormat(decimals, type == "percentage", currency, grouping, type == "date")+        }+        while (e != XmlPullParser.END_DOCUMENT) {+            when (e) {+                XmlPullParser.START_TAG -> when (parser.name) {+                    "number-style", "percentage-style", "currency-style", "date-style" -> {+                        curName = getAttr(parser, "name"); type = parser.name.removeSuffix("-style")+                        decimals = null; currency = null; grouping = false+                    }+                    "number" -> {+                        getAttr(parser, "decimal-places")?.toIntOrNull()?.let { decimals = it }+                        if (getAttr(parser, "grouping") == "true") grouping = true+                    }+                    "currency-symbol" -> {+                        val d = parser.depth; var ev = parser.next(); val sb = StringBuilder()+                        while (!(ev == XmlPullParser.END_TAG && parser.depth == d)) {+                            if (ev == XmlPullParser.TEXT) sb.append(parser.text)+                            if (ev == XmlPullParser.END_DOCUMENT) break+                            ev = parser.next()+                        }+                        currency = sb.toString().trim()+                    }+                }+                XmlPullParser.END_TAG -> when (parser.name) {+                    "number-style", "percentage-style", "currency-style", "date-style" -> { flush(); curName = null }+                }+            }+            e = parser.next()+        }+        return map+    }+     // --- Metadata parsing ---      private fun parseMetadata(xml: String): OdfMetadata {@@ -440,7 +580,8 @@ object OdfParser {         footnotes: MutableList<OdfFootnote>? = null,         imagesOut: MutableList<OdfImage>? = null,         objectContents: Map<String, String> = emptyMap(),-        chartsOut: MutableList<OdfChart>? = null+        chartsOut: MutableList<OdfChart>? = null,+        formulasOut: MutableList<String>? = null     ): List<OdfSpan> {         val spans = mutableListOf<OdfSpan>()         val depth = parser.depth@@ -448,6 +589,8 @@ object OdfParser {         val textBuffer = StringBuilder()         var currentStyleName: String? = null         var currentHref: String? = null+        var pendingFrameW = 0f+        var pendingFrameH = 0f          while (!(eventType == XmlPullParser.END_TAG && parser.depth == depth && parser.name == endTag)) {             when (eventType) {@@ -469,14 +612,52 @@ object OdfParser {                     "tab" -> textBuffer.append("\t")                     "s" -> textBuffer.append(" ".repeat((getAttr(parser, "c")?.toIntOrNull() ?: 1)))                     "line-break" -> textBuffer.append("\n")+                    "frame" -> {+                        pendingFrameW = parseDimension(getAttr(parser, "width"))+                        pendingFrameH = parseDimension(getAttr(parser, "height"))+                    }                     "image" -> {                         val href = getAttr(parser, "href")-                        if (href != null && images.containsKey(href)) imagesOut?.add(OdfImage(path = href, imageData = images[href]!!))+                        val w = pendingFrameW+                        val h = pendingFrameH+                        if (href != null && images.containsKey(href)) {+                            imagesOut?.add(OdfImage(path = href, imageData = images[href]!!, width = w, height = h))+                            skipElement(parser)+                        } else {+                            // Look for inline base64 binary-data. (A2/E37)+                            val imgDepth = parser.depth+                            var imgEvent = parser.next()+                            while (!(imgEvent == XmlPullParser.END_TAG && parser.depth == imgDepth)) {+                                if (imgEvent == XmlPullParser.START_TAG && parser.name == "binary-data") {+                                    imgEvent = parser.next()+                                    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))+                                        } catch (_: Exception) {}+                                    }+                                }+                                imgEvent = parser.next()+                            }+                            // No real image data found (e.g. an object-replacement preview for a chart);+                            // skip rather than emitting an empty "[Image]" placeholder.+                        }                     }                     "object" -> {                         val href = getAttr(parser, "href")?.removePrefix("./")                         val xml = href?.let { objectContents["$it/content.xml"] }-                        if (xml != null) parseChart(xml)?.let { chartsOut?.add(it) }+                        if (xml != null) {+                            val chart = parseChart(xml)+                            when {+                                chart != null -> chartsOut?.add(chart)+                                xml.contains("math") -> formulasOut?.add(xml)+                                xml.contains("office:spreadsheet") -> formulasOut?.add("\uD83D\uDCCA [Embedded spreadsheet]")+                                xml.contains("office:text") -> formulasOut?.add("\uD83D\uDCC4 [Embedded document]")+                                else -> formulasOut?.add("\uD83D\uDCE6 [Embedded object]")+                            }+                        } else if (href != null) {+                            formulasOut?.add("\uD83D\uDCE6 [Embedded object]")+                        }                     }                     "note" -> {                         if (textBuffer.isNotEmpty()) {@@ -600,7 +781,7 @@ object OdfParser {     // --- Text Document ---      private fun parseTextDocument(-        xml: String, styles: Map<String, StyleInfo>, listStyles: Map<String, ListType>,+        xml: String, styles: Map<String, StyleInfo>, listStyles: Map<String, ListStyleInfo>,         title: String, metadata: OdfMetadata, images: Map<String, ByteArray>,         headerFooter: HeaderFooterResult?, objectContents: Map<String, String> = emptyMap()     ): OdfDocument.TextDocument {@@ -612,6 +793,7 @@ object OdfParser {         var listDepth = 0         val listTypeStack = mutableListOf<ListType>()         val listItemCounter = mutableListOf<Int>()+        val listStyleStack = mutableListOf<ListStyleInfo?>()         var eventType = parser.eventType          while (eventType != XmlPullParser.END_DOCUMENT) {@@ -629,18 +811,31 @@ object OdfParser {                         val resolved = resolveStyle(styleName, styles)                         val inlineImages = mutableListOf<OdfImage>()                         val inlineCharts = mutableListOf<OdfChart>()-                        val spans = parseInlineContent(parser, "h", styles, images, footnotes, inlineImages, objectContents, inlineCharts)+                        val inlineFormulas = mutableListOf<String>()+                        val spans = parseInlineContent(parser, "h", styles, images, footnotes, inlineImages, objectContents, inlineCharts, inlineFormulas)                         if (resolved.breakBefore == "page") content.add(OdfContentBlock.PageBreak)                         val direction = parseDirection(resolved.writingMode)+                        val hLevelStyle = if (listDepth > 0) listStyleStack.lastOrNull()?.levelStyle(listDepth) else null                         content.add(OdfContentBlock.Paragraph(OdfParagraph(                             spans = spans, style = paraStyle,                             alignment = resolved.textAlign, marginLeft = resolved.marginLeft,                             marginTop = resolved.marginTop, marginBottom = resolved.marginBottom,                             textIndent = resolved.textIndent, backgroundColor = resolved.paragraphBackgroundColor,-                            direction = direction+                            direction = direction,+                            lineHeightPercent = resolved.lineHeightPercent,+                            borderColor = resolved.paragraphBorderColor,+                            tabStops = resolved.tabStops,+                            listLevel = if (listDepth > 0) listDepth else 0,+                            listType = if (hLevelStyle?.numbered == true) ListType.NUMBERED else ListType.BULLET,+                            listItemIndex = if (listItemCounter.isNotEmpty()) listItemCounter.last() else 0,+                            listNumberFormat = hLevelStyle?.numberFormat ?: "1",+                            listBulletChar = hLevelStyle?.bulletChar ?: "\u2022",+                            listNumberPrefix = hLevelStyle?.prefix ?: "",+                            listNumberSuffix = hLevelStyle?.suffix ?: "."                         )))                         for (img in inlineImages) content.add(OdfContentBlock.Image(img))                         for (ch in inlineCharts) content.add(OdfContentBlock.Chart(ch))+                        for (f in inlineFormulas) content.add(if (f.contains("math")) OdfContentBlock.Formula(f) else OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text = f, italic = true)), alignment = TextAlign.Center)))                         if (resolved.breakAfter == "page") content.add(OdfContentBlock.PageBreak)                     }                     inBody && parser.name == "p" && parser.namespace?.contains("text") == true -> {@@ -650,35 +845,55 @@ object OdfParser {                         val style = if (listDepth > 0) ParagraphStyle.LIST_ITEM else ParagraphStyle.BODY                         val inlineImages = mutableListOf<OdfImage>()                         val inlineCharts = mutableListOf<OdfChart>()-                        val spans = parseInlineContent(parser, "p", styles, images, footnotes, inlineImages, objectContents, inlineCharts)+                        val inlineFormulas = mutableListOf<String>()+                        val spans = parseInlineContent(parser, "p", styles, images, footnotes, inlineImages, objectContents, inlineCharts, inlineFormulas)                         val direction = parseDirection(resolved.writingMode)                         if (spans.isNotEmpty() || listDepth > 0) {                             val itemIdx = if (listItemCounter.isNotEmpty()) listItemCounter.last() else 0+                            val levelStyle = listStyleStack.lastOrNull()?.levelStyle(listDepth)+                            val listTypeResolved = when {+                                levelStyle != null -> if (levelStyle.numbered) ListType.NUMBERED else ListType.BULLET+                                listTypeStack.isNotEmpty() -> listTypeStack.last()+                                else -> ListType.BULLET+                            }                             content.add(OdfContentBlock.Paragraph(OdfParagraph(                                 spans = spans, style = style,                                 alignment = resolved.textAlign, marginLeft = resolved.marginLeft,                                 marginTop = resolved.marginTop, marginBottom = resolved.marginBottom,                                 textIndent = resolved.textIndent, backgroundColor = resolved.paragraphBackgroundColor,                                 listLevel = listDepth,-                                listType = if (listTypeStack.isNotEmpty()) listTypeStack.last() else ListType.BULLET,+                                listType = listTypeResolved,                                 listItemIndex = itemIdx,-                                direction = direction+                                direction = direction,+                                lineHeightPercent = resolved.lineHeightPercent,+                                borderColor = resolved.paragraphBorderColor,+                                tabStops = resolved.tabStops,+                                listNumberFormat = levelStyle?.numberFormat ?: "1",+                                listBulletChar = levelStyle?.bulletChar ?: "\u2022",+                                listNumberPrefix = levelStyle?.prefix ?: "",+                                listNumberSuffix = levelStyle?.suffix ?: "."                             )))                         }                         for (img in inlineImages) content.add(OdfContentBlock.Image(img))                         for (ch in inlineCharts) content.add(OdfContentBlock.Chart(ch))+                        for (f in inlineFormulas) content.add(if (f.contains("math")) OdfContentBlock.Formula(f) else OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text = f, italic = true)), alignment = TextAlign.Center)))                         if (resolved.breakAfter == "page") content.add(OdfContentBlock.PageBreak)                     }                     inBody && parser.name == "list" -> {                         listDepth++                         val styleName = getAttr(parser, "style-name")+                        val styleInfo = when {+                            styleName != null -> listStyles[styleName] ?: listStyleStack.lastOrNull()+                            else -> listStyleStack.lastOrNull()+                        }                         val type = when {-                            styleName != null -> listStyles[styleName] ?: ListType.BULLET+                            styleInfo != null -> if (styleInfo.levelStyle(listDepth).numbered) ListType.NUMBERED else ListType.BULLET                             listTypeStack.isNotEmpty() -> listTypeStack.last()                             else -> ListType.BULLET                         }                         listTypeStack.add(type)                         listItemCounter.add(0)+                        listStyleStack.add(styleInfo)                     }                     inBody && parser.name == "list-item" -> {                         if (listItemCounter.isNotEmpty()) {@@ -705,6 +920,7 @@ object OdfParser {                         listDepth--                         if (listTypeStack.isNotEmpty()) listTypeStack.removeAt(listTypeStack.size - 1)                         if (listItemCounter.isNotEmpty()) listItemCounter.removeAt(listItemCounter.size - 1)+                        if (listStyleStack.isNotEmpty()) listStyleStack.removeAt(listStyleStack.size - 1)                     }                 }             }@@ -859,7 +1075,9 @@ object OdfParser {         }         val type = when {             chartClass?.contains("line") == true -> ChartType.LINE-            chartClass?.contains("circle") == true || chartClass?.contains("ring") == true -> ChartType.PIE+            chartClass?.contains("scatter") == true -> ChartType.SCATTER+            chartClass?.contains("ring") == true -> ChartType.DONUT+            chartClass?.contains("circle") == true -> ChartType.PIE             chartClass?.contains("area") == true -> ChartType.AREA             else -> ChartType.BAR         }@@ -867,10 +1085,24 @@ object OdfParser {         return if (categories.isEmpty()) null else OdfChart(type, categories, series)     } +    private fun parseFormulaText(xml: String): String? {+        if (!xml.contains("math")) return null+        val ann = Regex("<annotation[^>]*>(.*?)</annotation>", RegexOption.DOT_MATCHES_ALL).find(xml)?.groupValues?.get(1)+        if (!ann.isNullOrBlank()) return unescapeXml(ann.trim())+        var toks = Regex("<m:(mi|mn|mo)[^>]*>(.*?)</m:(mi|mn|mo)>", RegexOption.DOT_MATCHES_ALL).findAll(xml).map { it.groupValues[2] }.toList()+        if (toks.isEmpty()) toks = Regex("<(mi|mn|mo)[^>]*>(.*?)</(mi|mn|mo)>", RegexOption.DOT_MATCHES_ALL).findAll(xml).map { it.groupValues[2] }.toList()+        val joined = toks.joinToString(" ").trim()+        return if (joined.isBlank()) null else unescapeXml(joined)+    }++    private fun unescapeXml(s: String): String = s+        .replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"")+        .replace("&apos;", "'").replace("&amp;", "&")+     // --- Spreadsheet ---      private fun parseSpreadsheet(-        xml: String, styles: Map<String, StyleInfo>,+        xml: String, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>,         title: String, metadata: OdfMetadata, images: Map<String, ByteArray>     ): OdfDocument.Spreadsheet {         val sheets = mutableListOf<OdfSheet>()@@ -880,7 +1112,7 @@ object OdfParser {         while (eventType != XmlPullParser.END_DOCUMENT) {             if (eventType == XmlPullParser.START_TAG && parser.name == "table" && parser.namespace?.contains("table") == true) {                 val name = getAttr(parser, "name") ?: "Sheet ${sheets.size + 1}"-                val result = parseSheetContent(parser, styles)+                val result = parseSheetContent(parser, styles, numberStyles)                 sheets.add(OdfSheet(name, result.first, result.second))             }             eventType = parser.next()@@ -888,7 +1120,7 @@ object OdfParser {         return OdfDocument.Spreadsheet(title, sheets, metadata, images)     } -    private fun parseSheetContent(parser: XmlPullParser, styles: Map<String, StyleInfo>): Pair<List<OdfRow>, List<Float?>> {+    private fun parseSheetContent(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>): Pair<List<OdfRow>, List<Float?>> {         val rows = mutableListOf<OdfRow>()         val columnWidths = mutableListOf<Float?>()         val depth = parser.depth@@ -898,19 +1130,28 @@ object OdfParser {             if (eventType == XmlPullParser.START_TAG) when (parser.name) {                 "table-column" -> {                     val repeated = getAttr(parser, "number-columns-repeated")?.toIntOrNull() ?: 1-                    repeat(repeated.coerceAtMost(200)) { columnWidths.add(null) }+                    val styleName = getAttr(parser, "style-name")+                    val width = resolveStyle(styleName, styles).columnWidth+                    repeat(repeated.coerceAtMost(200)) { columnWidths.add(width) }                 }                 "table-row" -> {-                    val cells = parseSpreadsheetCells(parser, styles)-                    if (cells.any { it.text.isNotEmpty() }) rows.add(OdfRow(cells))+                    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)) }                 }             }             eventType = parser.next()         }+        // Trim trailing all-empty rows.+        while (rows.isNotEmpty() && rows.last().cells.all { it.text.isEmpty() && it.formula == null }) {+            rows.removeAt(rows.size - 1)+        }         return Pair(rows, columnWidths)     } -    private fun parseSpreadsheetCells(parser: XmlPullParser, styles: Map<String, StyleInfo>): List<OdfCell> {+    private fun parseSpreadsheetCells(parser: XmlPullParser, styles: Map<String, StyleInfo>, numberStyles: Map<String, OdfNumberFormat>): List<OdfCell> {         val cells = mutableListOf<OdfCell>()         val depth = parser.depth         var eventType = parser.next()@@ -923,13 +1164,19 @@ object OdfParser {                     val repeated = getAttr(parser, "number-columns-repeated")?.toIntOrNull() ?: 1                     val styleName = getAttr(parser, "style-name")                     val resolved = resolveStyle(styleName, styles)+                    val formula = getAttr(parser, "formula")+                    val valueType = getAttr(parser, "value-type")+                    val numberValue = getAttr(parser, "value")?.toDoubleOrNull()+                    val numberFormat = resolved.dataStyleName?.let { numberStyles[it] }                     val text = parseCellText(parser)                     repeat(repeated.coerceAtMost(100)) {                         cells.add(OdfCell(                             text = text, spannedColumns = spanned, rowSpan = rowSpan,                             backgroundColor = resolved.cellBackgroundColor, textColor = resolved.color,                             bold = resolved.bold, italic = resolved.italic, alignment = resolved.textAlign,-                            borderColor = resolved.cellBorderColor+                            borderColor = resolved.cellBorderColor,+                            formula = formula, valueType = valueType, numberValue = numberValue,+                            numberFormat = numberFormat, wrap = resolved.cellWrap                         ))                     }                 }@@ -1029,6 +1276,7 @@ object OdfParser {         val y = parseDimension(getAttr(parser, "y"))         val w = parseDimension(getAttr(parser, "width"))         val h = parseDimension(getAttr(parser, "height"))+        val rot = parseRotationDegrees(getAttr(parser, "transform"))         val styleName = getAttr(parser, "style-name")         val resolved = resolveStyle(styleName, styles) @@ -1055,7 +1303,7 @@ object OdfParser {                 "image" -> {                     val href = getAttr(parser, "href")                     if (href != null && images.containsKey(href)) {-                        image = OdfImage(path = href, imageData = images[href]!!, width = w, height = h)+                        image = OdfImage(path = href, imageData = images[href]!!, width = w, height = h, rotationDegrees = rot)                     }                     val imgDepth = parser.depth                     var imgEvent = parser.next()@@ -1065,7 +1313,7 @@ object OdfParser {                             if (imgEvent == XmlPullParser.TEXT) {                                 try {                                     val bytes = Base64.decode(parser.text.trim(), Base64.DEFAULT)-                                    image = OdfImage(path = "inline", imageData = bytes, width = w, height = h)+                                    image = OdfImage(path = "inline", imageData = bytes, width = w, height = h, rotationDegrees = rot)                                 } catch (_: Exception) { }                             }                         }
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 6d700c181f..045385deff 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfSerializer.kt@@ -15,6 +15,42 @@ object OdfSerializer {         }     } +    /** Serializes to a flat ODF (.fodt/.fods/.fodp) single-XML document (K75). */+    fun serializeFlat(document: OdfDocument): String {+        val content = serialize(document)+        val mimetype = when (document) {+            is OdfDocument.TextDocument -> "application/vnd.oasis.opendocument.text"+            is OdfDocument.Spreadsheet -> "application/vnd.oasis.opendocument.spreadsheet"+            is OdfDocument.Presentation -> "application/vnd.oasis.opendocument.presentation"+            is OdfDocument.Drawing -> "application/vnd.oasis.opendocument.graphics"+        }+        val metaFull = serializeMeta(document.metadata)+        val metaInner = if (metaFull.contains("<office:meta>"))+            "<office:meta>" + metaFull.substringAfter("<office:meta>").substringBefore("</office:meta>") + "</office:meta>"+        else ""+        var s = content.replace("<office:document-content", "<office:document")+        s = s.replace("""office:version="1.3">""", """office:mimetype="$mimetype" office:version="1.3">$metaInner""")+        s = s.replace("</office:document-content>", "</office:document>")+        return s+    }++    /** Generates meta.xml so edited document metadata persists on save (G47). */+    fun serializeMeta(meta: OdfMetadata): String {+        val sb = StringBuilder()+        sb.append("""<?xml version="1.0" encoding="UTF-8"?>""")+        sb.append("""<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" office:version="1.3"><office:meta>""")+        meta.title?.let { sb.append("<dc:title>${esc(it)}</dc:title>") }+        meta.creator?.let { sb.append("<meta:initial-creator>${esc(it)}</meta:initial-creator>") }+        meta.author?.let { sb.append("<dc:creator>${esc(it)}</dc:creator>") }+        meta.subject?.let { sb.append("<dc:subject>${esc(it)}</dc:subject>") }+        meta.description?.let { sb.append("<dc:description>${esc(it)}</dc:description>") }+        for (kw in meta.keywords) sb.append("<meta:keyword>${esc(kw)}</meta:keyword>")+        meta.creationDate?.let { sb.append("<meta:creation-date>${esc(it)}</meta:creation-date>") }+        meta.modifiedDate?.let { sb.append("<dc:date>${esc(it)}</dc:date>") }+        sb.append("</office:meta></office:document-meta>")+        return sb.toString()+    }+     private fun serializeTextDocument(doc: OdfDocument.TextDocument): String {         val styles = mutableMapOf<String, SpanStyleDef>()         val paraStyles = mutableMapOf<String, ParaStyleDef>()@@ -52,6 +88,10 @@ object OdfSerializer {                     if (listOpen) { body.append("</text:list>"); listOpen = false }                     // Charts are embedded OLE objects; not re-serialized (preserved only when not re-saved).                 }+                is OdfContentBlock.Formula -> {+                    if (listOpen) { body.append("</text:list>"); listOpen = false }+                    // Formulas are embedded math objects; preserved via original package, not re-serialized inline.+                }                 is OdfContentBlock.PageBreak -> {                     if (listOpen) { body.append("</text:list>"); listOpen = false }                 }@@ -59,16 +99,24 @@ object OdfSerializer {         }         if (listOpen) body.append("</text:list>") -        return buildDocument("office:text", styles, paraStyles, body.toString())+        return buildDocument("office:text", styles, paraStyles, LinkedHashMap(), LinkedHashMap(), body.toString())     }      private fun serializeSpreadsheet(doc: OdfDocument.Spreadsheet): String {+        val cellStyles = LinkedHashMap<String, CellStyleDef>()+        val colStyles = LinkedHashMap<String, Float>()         val body = StringBuilder()         for (sheet in doc.sheets) {             body.append("""<table:table table:name="${esc(sheet.name)}">""")             val maxCols = sheet.rows.maxOfOrNull { it.cells.size } ?: 0-            if (maxCols > 0) {-                body.append("""<table:table-column table:number-columns-repeated="$maxCols"/>""")+            for (c in 0 until maxCols) {+                val w = sheet.columnWidths.getOrNull(c)+                if (w != null && w > 0f) {+                    val name = getOrCreateColStyle(w, colStyles)+                    body.append("""<table:table-column table:style-name="$name"/>""")+                } else {+                    body.append("<table:table-column/>")+                }             }             for (row in sheet.rows) {                 body.append("<table:table-row>")@@ -77,13 +125,19 @@ object OdfSerializer {                         body.append("<table:covered-table-cell/>")                     } else {                         body.append("<table:table-cell")+                        val styleName = getOrCreateCellStyle(cell, cellStyles)+                        if (styleName != null) body.append(""" table:style-name="$styleName"""")                         if (cell.spannedColumns > 1) body.append(""" table:number-columns-spanned="${cell.spannedColumns}"""")                         if (cell.rowSpan > 1) body.append(""" table:number-rows-spanned="${cell.rowSpan}"""")-                        if (cell.text.isNotEmpty()) body.append(""" office:value-type="string"""")-                        body.append(">")-                        if (cell.text.isNotEmpty()) {-                            body.append("<text:p>${esc(cell.text)}</text:p>")+                        if (cell.formula != null) body.append(""" table:formula="${esc(cell.formula)}"""")+                        val numeric = cell.numberValue ?: cell.text.toDoubleOrNull()+                        if (numeric != null && cell.valueType != "string") {+                            body.append(""" office:value-type="float" office:value="$numeric"""")+                        } else if (cell.text.isNotEmpty()) {+                            body.append(""" office:value-type="string"""")                         }+                        body.append(">")+                        if (cell.text.isNotEmpty()) body.append("<text:p>${esc(cell.text)}</text:p>")                         body.append("</table:table-cell>")                     }                 }@@ -91,7 +145,7 @@ object OdfSerializer {             }             body.append("</table:table>")         }-        return buildDocument("office:spreadsheet", mutableMapOf(), mutableMapOf(), body.toString())+        return buildDocument("office:spreadsheet", mutableMapOf(), mutableMapOf(), cellStyles, colStyles, body.toString())     }      private fun serializePresentation(doc: OdfDocument.Presentation): String {@@ -108,7 +162,7 @@ object OdfSerializer {             }             body.append("</draw:page>")         }-        return buildDocument("office:presentation", styles, paraStyles, body.toString())+        return buildDocument("office:presentation", styles, paraStyles, LinkedHashMap(), LinkedHashMap(), body.toString())     }      private fun serializeParagraph(@@ -234,7 +288,37 @@ object OdfSerializer {         val superscript: Boolean = false, val subscript: Boolean = false     ) -    private data class ParaStyleDef(val alignment: TextAlign? = null)+    private data class ParaStyleDef(+        val alignment: TextAlign? = null,+        val marginLeft: Float = 0f,+        val textIndent: Float = 0f,+        val lineHeightPercent: Float? = null,+        val borderColor: Long? = null,+        val backgroundColor: Long? = null+    )++    private data class CellStyleDef(+        val backgroundColor: Long? = null, val textColor: Long? = null,+        val bold: Boolean = false, val italic: Boolean = false,+        val alignment: TextAlign? = null, val borderColor: Long? = null+    )++    private fun getOrCreateCellStyle(cell: OdfCell, styles: MutableMap<String, CellStyleDef>): String? {+        if (cell.backgroundColor == null && cell.textColor == null && !cell.bold && !cell.italic &&+            cell.alignment == null && cell.borderColor == null) return null+        val def = CellStyleDef(cell.backgroundColor, cell.textColor, cell.bold, cell.italic, cell.alignment, cell.borderColor)+        for ((name, existing) in styles) if (existing == def) return name+        val name = "ce${styles.size + 1}"+        styles[name] = def+        return name+    }++    private fun getOrCreateColStyle(width: Float, styles: MutableMap<String, Float>): String {+        for ((name, existing) in styles) if (existing == width) return name+        val name = "co${styles.size + 1}"+        styles[name] = width+        return name+    }      private fun getOrCreateSpanStyle(span: OdfSpan, styles: MutableMap<String, SpanStyleDef>): String {         val def = SpanStyleDef(span.bold, span.italic, span.underline, span.strikethrough,@@ -246,8 +330,10 @@ object OdfSerializer {     }      private fun getOrCreateParaStyle(para: OdfParagraph, styles: MutableMap<String, ParaStyleDef>): String? {-        if (para.alignment == null) return null-        val def = ParaStyleDef(para.alignment)+        val hasProps = para.alignment != null || para.marginLeft != 0f || para.textIndent != 0f ||+            para.lineHeightPercent != null || para.borderColor != null || para.backgroundColor != null+        if (!hasProps) return null+        val def = ParaStyleDef(para.alignment, para.marginLeft, para.textIndent, para.lineHeightPercent, para.borderColor, para.backgroundColor)         for ((name, existing) in styles) if (existing == def) return name         val name = "P${styles.size + 1}"         styles[name] = def@@ -260,6 +346,8 @@ object OdfSerializer {         bodyType: String,         spanStyles: Map<String, SpanStyleDef>,         paraStyles: Map<String, ParaStyleDef>,+        cellStyles: Map<String, CellStyleDef>,+        colStyles: Map<String, Float>,         bodyContent: String     ): String {         val sb = StringBuilder()@@ -297,6 +385,33 @@ object OdfSerializer {                 TextAlign.Justify -> sb.append(""" fo:text-align="justify"""")                 else -> {}             }+            if (def.marginLeft != 0f) sb.append(""" fo:margin-left="${def.marginLeft / 37.8f}cm"""")+            if (def.textIndent != 0f) sb.append(""" fo:text-indent="${def.textIndent / 37.8f}cm"""")+            if (def.lineHeightPercent != null) sb.append(""" fo:line-height="${(def.lineHeightPercent * 100).toInt()}%"""")+            if (def.borderColor != null) sb.append(""" fo:border="0.5pt solid ${formatColor(def.borderColor)}"""")+            if (def.backgroundColor != null) sb.append(""" fo:background-color="${formatColor(def.backgroundColor)}"""")+            sb.append("/></style:style>")+        }+        for ((name, width) in colStyles) {+            sb.append("""<style:style style:name="$name" style:family="table-column"><style:table-column-properties style:column-width="${width / 37.8f}cm"/></style:style>""")+        }+        for ((name, def) in cellStyles) {+            sb.append("""<style:style style:name="$name" style:family="table-cell">""")+            sb.append("<style:table-cell-properties")+            if (def.backgroundColor != null) sb.append(""" fo:background-color="${formatColor(def.backgroundColor)}"""")+            if (def.borderColor != null) sb.append(""" fo:border="0.5pt solid ${formatColor(def.borderColor)}"""")+            sb.append("/>")+            when (def.alignment) {+                TextAlign.Start, TextAlign.Left -> sb.append("""<style:paragraph-properties fo:text-align="start"/>""")+                TextAlign.Center -> sb.append("""<style:paragraph-properties fo:text-align="center"/>""")+                TextAlign.End, TextAlign.Right -> sb.append("""<style:paragraph-properties fo:text-align="end"/>""")+                TextAlign.Justify -> sb.append("""<style:paragraph-properties fo:text-align="justify"/>""")+                else -> {}+            }+            sb.append("<style:text-properties")+            if (def.bold) sb.append(""" fo:font-weight="bold"""")+            if (def.italic) sb.append(""" fo:font-style="italic"""")+            if (def.textColor != null) sb.append(""" fo:color="${formatColor(def.textColor)}"""")             sb.append("/></style:style>")         }         sb.append("</office:automatic-styles>")
office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt b/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.ktindex 3ae55c811c..d591679581 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OdfWriter.kt@@ -11,6 +11,9 @@ object OdfWriter {      fun save(context: Context, sourceUri: Uri, document: OdfDocument, targetUri: Uri) {         val contentXml = OdfSerializer.serialize(document)+        val metaXml = OdfSerializer.serializeMeta(document.metadata)+        val docImages = imagesOf(document)+        val written = mutableSetOf<String>()          val buffer = ByteArrayOutputStream()         ZipOutputStream(buffer).use { zipOut ->@@ -22,15 +25,37 @@ object OdfWriter {                             zipOut.putNextEntry(ZipEntry("content.xml"))                             zipOut.write(contentXml.toByteArray(Charsets.UTF_8))                             zipOut.closeEntry()+                            written.add("content.xml")+                        } else if (entry.name == "meta.xml") {+                            zipOut.putNextEntry(ZipEntry("meta.xml"))+                            zipOut.write(metaXml.toByteArray(Charsets.UTF_8))+                            zipOut.closeEntry()+                            written.add("meta.xml")                         } else if (!entry.isDirectory) {                             zipOut.putNextEntry(ZipEntry(entry.name))                             zipIn.copyTo(zipOut)                             zipOut.closeEntry()+                            written.add(entry.name)                         }                         entry = zipIn.nextEntry                     }                 }             }+            // If the source had no content.xml (e.g. brand-new flat/empty), ensure one is written.+            if ("content.xml" !in written) {+                zipOut.putNextEntry(ZipEntry("content.xml"))+                zipOut.write(contentXml.toByteArray(Charsets.UTF_8))+                zipOut.closeEntry()+                written.add("content.xml")+            }+            // Write any newly-inserted images that weren't part of the original package. (K72/K73)+            for ((path, bytes) in docImages) {+                if (path == "inline" || path in written || bytes.isEmpty()) continue+                zipOut.putNextEntry(ZipEntry(path))+                zipOut.write(bytes)+                zipOut.closeEntry()+                written.add(path)+            }         }          context.contentResolver.openOutputStream(targetUri, "wt")?.use { output ->@@ -38,6 +63,13 @@ object OdfWriter {         }     } +    private fun imagesOf(document: OdfDocument): Map<String, ByteArray> = when (document) {+        is OdfDocument.TextDocument -> document.images+        is OdfDocument.Spreadsheet -> document.images+        is OdfDocument.Presentation -> document.images+        is OdfDocument.Drawing -> document.images+    }+     fun saveAs(context: Context, sourceUri: Uri, document: OdfDocument, targetUri: Uri) {         save(context, sourceUri, document, targetUri)     }
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 5ab0aae009..e525e5497d 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentViews.kt@@ -13,6 +13,7 @@ import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer@@ -20,9 +21,11 @@ import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width@@ -35,6 +38,8 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.ClickableText+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults@@ -49,6 +54,7 @@ import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf@@ -65,7 +71,10 @@ import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.draw.rotate import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.focus.FocusRequester+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@@ -76,6 +85,7 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.input.OffsetMapping+import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.text.input.VisualTransformation@@ -90,6 +100,8 @@ import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogProperties import com.vayunmathur.office.odf.*  // --- Headings for outline ---@@ -199,6 +211,82 @@ fun FontSizePickerDialog(onSizeSelected: (Float) -> Unit, onDismiss: () -> Unit)     ) } +// --- Special Characters Dialog ---++@Composable+fun SpecialCharsDialog(onPick: (String) -> Unit, onDismiss: () -> Unit) {+    val chars = listOf(+        "©", "®", "™", "°", "±", "×", "÷", "≈", "≠", "≤", "≥", "∞",+        "•", "·", "—", "–", "…", "§", "¶", "†", "‡", "★", "☆", "✓",+        "→", "←", "↑", "↓", "⇒", "⇔", "€", "£", "¥", "¢", "α", "β",+        "γ", "δ", "π", "Σ", "Ω", "µ", "½", "¼", "¾", "²", "³", "“"+    )+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text("Special Character") },+        text = {+            Column {+                for (row in chars.chunked(6)) {+                    Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+                        for (ch in row) {+                            Surface(+                                modifier = Modifier.size(40.dp).clickable { onPick(ch); onDismiss() },+                                shape = RoundedCornerShape(4.dp),+                                color = MaterialTheme.colorScheme.surfaceVariant+                            ) { Box(contentAlignment = Alignment.Center) { Text(ch, style = MaterialTheme.typography.titleMedium) } }+                        }+                    }+                    Spacer(Modifier.height(4.dp))+                }+            }+        },+        confirmButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }+    )+}++// --- Footnote / Comment / Header-Footer Dialogs ---++@Composable+fun FootnoteDialog(onAdd: (String) -> Unit, onDismiss: () -> Unit) {+    var text by remember { mutableStateOf("") }+    AlertDialog(onDismissRequest = onDismiss, title = { Text("Insert Footnote") },+        text = { TextField(value = text, onValueChange = { text = it }, label = { Text("Footnote text") }, modifier = Modifier.fillMaxWidth()) },+        confirmButton = { TextButton(onClick = { if (text.isNotBlank()) { onAdd(text); onDismiss() } }) { Text("Insert") } },+        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } })+}++@Composable+fun CommentDialog(onAdd: (author: String, text: String) -> Unit, onDismiss: () -> Unit) {+    var author by remember { mutableStateOf("") }+    var text by remember { mutableStateOf("") }+    AlertDialog(onDismissRequest = onDismiss, title = { Text("Insert Comment") },+        text = {+            Column {+                TextField(value = author, onValueChange = { author = it }, label = { Text("Author") }, singleLine = true, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(8.dp))+                TextField(value = text, onValueChange = { text = it }, label = { Text("Comment") }, modifier = Modifier.fillMaxWidth())+            }+        },+        confirmButton = { TextButton(onClick = { if (text.isNotBlank()) { onAdd(author, text); onDismiss() } }) { Text("Insert") } },+        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } })+}++@Composable+fun HeaderFooterDialog(initialHeader: String, initialFooter: String, onSave: (header: String, footer: String) -> Unit, onDismiss: () -> Unit) {+    var header by remember { mutableStateOf(initialHeader) }+    var footer by remember { mutableStateOf(initialFooter) }+    AlertDialog(onDismissRequest = onDismiss, title = { Text("Header & Footer") },+        text = {+            Column {+                TextField(value = header, onValueChange = { header = it }, label = { Text("Header") }, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(8.dp))+                TextField(value = footer, onValueChange = { footer = it }, label = { Text("Footer") }, modifier = Modifier.fillMaxWidth())+            }+        },+        confirmButton = { TextButton(onClick = { onSave(header, footer); onDismiss() }) { Text("Save") } },+        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } })+}+ // --- Insert Table Dialog ---  @Composable@@ -364,6 +452,51 @@ fun SortDialog(maxCols: Int, onSort: (colIndex: Int, ascending: Boolean) -> Unit     ) } +@Composable+fun ChartEditorDialog(initial: OdfChart?, onConfirm: (OdfChart) -> Unit, onDismiss: () -> Unit) {+    var type by remember { mutableStateOf(initial?.type ?: ChartType.BAR) }+    var categories by remember { mutableStateOf((initial?.categories ?: listOf("Category 1", "Category 2", "Category 3")).joinToString(", ")) }+    var seriesText by remember {+        mutableStateOf(+            (initial?.series ?: listOf(OdfChartSeries("Series 1", listOf(3f, 5f, 2f))))+                .joinToString("\n") { s -> s.name + ": " + s.values.joinToString(", ") { formatAxis(it) } }+        )+    }+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(if (initial == null) "Insert Chart" else "Edit Chart") },+        text = {+            Column {+                Row(Modifier.horizontalScroll(rememberScrollState()), verticalAlignment = Alignment.CenterVertically) {+                    Text("Type:", modifier = Modifier.padding(end = 4.dp))+                    for (t in ChartType.entries) {+                        TextButton(onClick = { type = t }) {+                            Text(t.name.lowercase().replaceFirstChar { it.uppercase() }, color = if (type == t) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface)+                        }+                    }+                }+                TextField(value = categories, onValueChange = { categories = it }, label = { Text("Categories (comma separated)") }, modifier = Modifier.fillMaxWidth())+                Spacer(Modifier.height(8.dp))+                TextField(value = seriesText, onValueChange = { seriesText = it }, label = { Text("Series (Name: v1, v2, ...)") }, modifier = Modifier.fillMaxWidth())+            }+        },+        confirmButton = {+            TextButton(onClick = {+                val cats = categories.split(",").map { it.trim() }.filter { it.isNotEmpty() }+                val series = seriesText.lines().mapNotNull { line ->+                    if (line.isBlank()) return@mapNotNull null+                    val name = (if (line.contains(":")) line.substringBefore(":") else "Series").trim().ifEmpty { "Series" }+                    val valsPart = if (line.contains(":")) line.substringAfter(":") else line+                    val vals = valsPart.split(",").mapNotNull { it.trim().toFloatOrNull() }+                    if (vals.isEmpty()) null else OdfChartSeries(name, vals)+                }+                if (cats.isNotEmpty() && series.isNotEmpty()) { onConfirm(OdfChart(type, cats, series)); onDismiss() }+            }) { Text("OK") }+        },+        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }+    )+}+ // --- Text Document (continuous editor) ---  private sealed class DocSegment {@@ -395,7 +528,8 @@ fun TextDocumentView(     onRunSelectionChange: (Int, Int, Int, Int) -> Unit = { _, _, _, _ -> },     onRunTextChange: (Int, Int, String) -> Unit = { _, _, _ -> },     onCellTextChange: (Int, Int, Int, String) -> Unit = { _, _, _, _ -> },-    onCellFocus: (Int, Int, Int) -> Unit = { _, _, _ -> }+    onCellFocus: (Int, Int, Int) -> Unit = { _, _, _ -> },+    onChartClick: (Int) -> Unit = {} ) {     val segments = remember(doc.content) { buildSegments(doc.content) } @@ -422,7 +556,8 @@ fun TextDocumentView(                         else Box(modifier = Modifier.clickable { fullScreen = true }) { OdfImageView(block.image) }                     }                     is OdfContentBlock.PageBreak -> PageBreakView()-                    is OdfContentBlock.Chart -> OdfChartView(block.chart)+                    is OdfContentBlock.Chart -> OdfChartView(block.chart, onClick = { onChartClick(seg.index) })+                    is OdfContentBlock.Formula -> MathView(block.mathml)                     is OdfContentBlock.Paragraph -> {}                 }             }@@ -457,10 +592,42 @@ private fun headingSizeSp(style: ParagraphStyle): Float? = when (style) {     else -> null } -private fun listPrefix(para: OdfParagraph): String = when {-    para.style == ParagraphStyle.LIST_ITEM && para.listType == ListType.NUMBERED -> "${para.listItemIndex}.  "-    para.style == ParagraphStyle.LIST_ITEM -> "•  "-    else -> ""+/** Visible list prefix (indent + bullet/number) for a paragraph. (A1/F42) */+fun listPrefixFor(para: OdfParagraph): String {+    if (para.listLevel <= 0 && para.style != ParagraphStyle.LIST_ITEM) return ""+    val level = maxOf(para.listLevel, 1)+    val indent = "    ".repeat(level - 1)+    return if (para.listType == ListType.NUMBERED) {+        indent + para.listNumberPrefix + formatListNumber(para.listItemIndex, para.listNumberFormat) + para.listNumberSuffix + "  "+    } else {+        indent + para.listBulletChar + "  "+    }+}++/** OffsetMapping for list prefixes injected at the start of each paragraph in a run. (A1) */+private class PrefixOffsetMapping(+    private val origStarts: IntArray,+    private val transStarts: IntArray,+    private val prefixLens: IntArray,+    private val lens: IntArray,+    private val origLen: Int,+    private val transLen: Int+) : OffsetMapping {+    override fun originalToTransformed(offset: Int): Int {+        val o = offset.coerceIn(0, origLen)+        var p = 0+        for (i in origStarts.indices) { if (origStarts[i] <= o) p = i else break }+        val inPara = (o - origStarts[p]).coerceIn(0, lens[p])+        return (transStarts[p] + prefixLens[p] + inPara).coerceIn(0, transLen)+    }+    override fun transformedToOriginal(offset: Int): Int {+        val t = offset.coerceIn(0, transLen)+        var p = 0+        for (i in transStarts.indices) { if (transStarts[i] <= t) p = i else break }+        val afterPrefix = t - transStarts[p] - prefixLens[p]+        val inPara = afterPrefix.coerceIn(0, lens[p])+        return (origStarts[p] + inPara).coerceIn(0, origLen)+    } }  @Composable@@ -480,9 +647,11 @@ private fun ContinuousParagraphEditor(         tfv = TextFieldValue(plainText, TextRange(caret))     }     val onSurface = MaterialTheme.colorScheme.onSurface+    val prefixColor = MaterialTheme.colorScheme.onSurfaceVariant     val lens = remember(paras) { paras.map { p -> p.spans.sumOf { it.text.length } } }-    val transformation = remember(paras, fontSizeMultiplier, onSurface) {-        VisualTransformation { TransformedText(buildDocAnnotated(it.text, paras, lens, onSurface, fontSizeMultiplier), OffsetMapping.Identity) }+    val prefixes = remember(paras) { paras.map { listPrefixFor(it) } }+    val transformation = remember(paras, fontSizeMultiplier, onSurface, prefixColor) {+        VisualTransformation { buildDocTransformed(it.text, paras, lens, prefixes, onSurface, prefixColor, fontSizeMultiplier) }     }     BasicTextField(         value = tfv,@@ -499,44 +668,75 @@ private fun ContinuousParagraphEditor(     ) } -private fun buildDocAnnotated(text: String, paras: List<OdfParagraph>, lens: List<Int>, baseColor: Color, mult: Float): AnnotatedString = buildAnnotatedString {-    append(text)-    var base = 0-    for (i in paras.indices) {-        val pStart = base-        val pEnd = (base + lens[i]).coerceAtMost(text.length)-        val para = paras[i]-        val paraEnd = if (i < paras.size - 1) (pEnd + 1).coerceAtMost(text.length) else text.length-        addStyle(-            androidx.compose.ui.text.ParagraphStyle(-                textAlign = para.alignment ?: TextAlign.Unspecified,-                textIndent = if (para.style == ParagraphStyle.LIST_ITEM || para.marginLeft > 0) androidx.compose.ui.text.style.TextIndent(firstLine = 0.sp, restLine = 0.sp) else androidx.compose.ui.text.style.TextIndent.None-            ),-            pStart, paraEnd-        )-        headingSizeSp(para.style)?.let { addStyle(SpanStyle(fontSize = (it * mult).sp, fontWeight = FontWeight.Bold), pStart, pEnd) }-        var off = pStart-        for (span in para.spans) {-            val segEnd = (off + span.text.length).coerceAtMost(pEnd)-            if (segEnd > off) {-                val decorations = mutableListOf<TextDecoration>()-           

Diff truncated.