Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Edit Word documents and workbooks with their engines; a readable selection menu; .xls opens
chethan616b84a6b91a566
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.ktindex d90c981..43fc91d 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppIcons.kt@@ -58,6 +58,10 @@ object LucideIcons {val FilePlus2: ImageVector get() = Icons.AutoMirrored.Rounded.NoteAddval FileStack: ImageVector get() = Icons.Rounded.FileCopyval FileText: ImageVector get() = Icons.Rounded.Description+ val Italic: ImageVector get() = Icons.Rounded.FormatItalic+ val ListOrdered: ImageVector get() = Icons.Rounded.FormatListNumbered+ val FilePdf: ImageVector get() = Icons.Rounded.PictureAsPdf+ val SaveAs: ImageVector get() = Icons.Rounded.SaveAsval ArrowUpRight: ImageVector get() = Icons.AutoMirrored.Rounded.OpenInNewval Files: ImageVector get() = Icons.Rounded.FileCopyval Presentation: ImageVector get() = Icons.Rounded.Slideshowdiff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.ktindex 982d59f..0a7db86 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt@@ -354,7 +354,10 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrval eng = engine ?: return falseif (!doc.info.dirty && !doc.notWrittenBack) return truereturn try {- if (doc.info.dirty) eng.tool("doc_save", mapOf("doc" to doc.id))+ // an office document is saved by its own engine, in its own format, into the working copy+ if (doc.info.dirty) {+ if (doc.isOffice) eng.command { saveOffice(doc.id, doc.file.absolutePath) } else eng.tool("doc_save", mapOf("doc" to doc.id))+ }refresh(doc)val src = doc.sourceif (src != null && src.scheme == "content") {@@ -2398,6 +2401,52 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr/** The note open in the editor. */var openNote by mutableStateOf<String?>(null)+ /** The Word document being edited (typing and formatting with WordCraft), if one is. */+ var wordEditing by mutableStateOf<OpenDocument?>(null)++ /** Where the caret (or the selection) is in [wordEditing]. */+ var wordCaret by mutableStateOf<com.chethan616.clearpdf.core.WordCaret?>(null)++ /** WordCraft's formatting at the caret (`bold`, `italic`, ... as `format.state` gives it). */+ var wordFormat by mutableStateOf(org.json.JSONObject())++ /** Start editing Word document [doc]: a tap places the caret, the keyboard types. */+ fun startWordEdit(doc: OpenDocument) {+ wordEditing = doc+ doc.selection.clear()+ doc.controller.barsVisible = true+ viewModelScope.launch { refreshWordCaret(doc) }+ }++ /** Leave editing; the changes are saved with the document (as on closing it). */+ fun stopWordEdit() {+ val doc = wordEditing ?: return+ wordEditing = null+ wordCaret = null+ viewModelScope.launch { save(doc, quiet = true) }+ }++ /** Run WordCraft command [command] on [doc], then show its result: the pages, caret and formatting. */+ fun wordRun(doc: OpenDocument, command: String, params: Map<String, Any?> = emptyMap()) {+ val eng = engine ?: return+ viewModelScope.launch {+ val json = Engine.toJson(params).toString()+ runCatching { eng.command { wordCommand(doc.id, command, json) } }+ .onSuccess { refresh(doc); refreshWordCaret(doc) }+ .onFailure { tell(it.userMessage) }+ }+ }++ /** A tap on [doc]'s page while editing: the caret goes there ([extend]: the selection grows to it). */+ fun wordTap(doc: OpenDocument, at: com.chethan616.clearpdf.ui.viewer.PagePoint, extend: Boolean = false) =+ wordRun(doc, "caret.set", mapOf("page" to at.page, "x" to at.x, "y" to at.y, "extend" to extend))++ private suspend fun refreshWordCaret(doc: OpenDocument) {+ val eng = engine ?: return+ wordCaret = runCatching { eng.command { wordCaret(doc.id) } }.getOrNull()+ wordFormat = runCatching { org.json.JSONObject(eng.command { wordCommand(doc.id, "format.state", "") }) }.getOrDefault(org.json.JSONObject())+ }+/** A presentation shown full screen, slide by slide. */var presenting by mutableStateOf<OpenDocument?>(null)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.ktindex 516b98f..40d8175 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt@@ -91,8 +91,8 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val t// office documents' own tools (their engines: WordCraft, DeckCraft)Present("present", R.string.office_present, R.string.office_present, LucideIcons.Presentation, ToolHues.read),- ExportPdf("exportpdf", R.string.office_export_pdf, R.string.office_export_pdf, LucideIcons.FileOutput, ToolHues.export),- SaveAs("saveas", R.string.office_save_as, R.string.office_save_as, LucideIcons.Copy, ToolHues.export),+ ExportPdf("exportpdf", R.string.office_export_pdf, R.string.office_export_pdf, LucideIcons.FilePdf, ToolHues.export),+ SaveAs("saveas", R.string.office_save_as, R.string.office_save_as, LucideIcons.SaveAs, ToolHues.export),Print("print", R.string.sheet_print, R.string.sheet_print, LucideIcons.Printer, ToolHues.export);companion object {@@ -100,7 +100,7 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val tval DEFAULT_BAR = listOf(Edit, Comment, Highlight, Draw, FillSign, Export)/** A Word document's bar: its engine reads it aloud, exports and converts it, and prints it. */- val WORD = listOf(ReadAloud, ExportPdf, SaveAs, Print)+ val WORD = listOf(Edit, ReadAloud, ExportPdf, SaveAs, Print)/** A presentation's bar: a full-screen show first. */val SLIDES = listOf(Present, ReadAloud, ExportPdf, SaveAs, Print)@@ -160,7 +160,8 @@ fun AppViewModel.runQuickTool(doc: OpenDocument, tool: QuickTool) {return}when (tool) {- QuickTool.Edit -> enterTool(doc, ViewerTool.Edit)+ // a Word document is edited by its own engine: typing and formatting, not PDF editing+ QuickTool.Edit -> if (doc.isOffice) startWordEdit(doc) else enterTool(doc, ViewerTool.Edit)QuickTool.Comment -> enterTool(doc, ViewerTool.Comment)QuickTool.Highlight -> enterTool(doc, ViewerTool.Markup)QuickTool.Draw -> enterTool(doc, ViewerTool.Draw)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.ktindex 4d1f892..b0402aa 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerOverlays.kt@@ -64,7 +64,8 @@ import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.IntOffsetimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.sp-import com.chethan616.clearpdf.ui.glass.glass+import com.chethan616.clearpdf.ui.glass.pressable+import com.kyant.backdrop.floatingLayerimport com.chethan616.clearpdf.ui.theme.clearimport com.chethan616.clearpdf.Rimport com.chethan616.clearpdf.core.CommentInfo@@ -206,14 +207,28 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)vm.addMarkup(doc, m, page, sel.rects, prefs.color(m.styled), prefs.opacity(m.styled))doc.selection.clear()}- Column(+ // the desk menu's glass and motion: frosted (the page never shows through the words), unfolding+ // out of the selection on the glass spring+ val appear = remember { androidx.compose.animation.core.Animatable(0f) }+ LaunchedEffect(Unit) { appear.animateTo(1f, com.chethan616.clearpdf.ui.glass.GlassMotion.unfold()) }+ val opensDown = y > top.y+ com.chethan616.clearpdf.ui.glass.GlassCard(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }.onSizeChanged { menuSize = it }- .width(220.dp)- // a liquid-glass popover over the pages, as every menu in the app- .glass(com.chethan616.clearpdf.ui.glass.RoundedRectangle(26.dp)),+ .width(236.dp)+ .floatingLayer {+ val p = appear.value+ scaleX = 0.6f + 0.4f * p+ scaleY = 0.4f + 0.6f * p+ transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, if (opensDown) 0f else 1f)+ alpha = (p * 1.6f).coerceIn(0f, 1f)+ },+ shape = com.chethan616.clearpdf.ui.glass.RoundedRectangle(24.dp),+ wash = clear.frost,+ blur = 16.dp,) {+ Spacer(Modifier.height(6.dp))// a Word document or presentation opens for reading: no markup, no Edit textif (!doc.isOffice) Row(Modifier.fillMaxWidth().height(61.dp), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {MenuIcon(LucideIcons.MessageSquarePlus, stringResource(R.string.viewer_add_comment), allowed) { vm.notePrompt = NotePrompt(doc, null, sel) }@@ -221,9 +236,9 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)MenuIcon(LucideIcons.Underline, stringResource(R.string.common_tool_underline), allowed) { markup(TextMarkup.Underline) }MenuIcon(LucideIcons.Strikethrough, stringResource(R.string.viewer_strikethrough), allowed) { markup(TextMarkup.Strikethrough) }}- // an inset divider, then the rows with 8 dp above and below+ // an inset divider, then the rowsif (!doc.isOffice) Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(1.dp).background(clear.ink.copy(alpha = 0.12f)))- Spacer(Modifier.height(8.dp))+ if (!doc.isOffice) Spacer(Modifier.height(4.dp))if (!doc.isOffice && (doc.writable || doc.source == null)) MenuRow(LucideIcons.FilePenLine, stringResource(R.string.viewer_edit_text)) {doc.selection.clear()vm.enterTool(doc, ViewerTool.Edit)@@ -234,7 +249,7 @@ fun BoxScope.SelectionMenu(vm: AppViewModel, doc: OpenDocument, sel: Selection)vm.startReadAloud(doc, fromSelection = true)doc.selection.clear()}- Spacer(Modifier.height(8.dp))+ Spacer(Modifier.height(6.dp))}}@@ -251,11 +266,11 @@ private fun MenuIcon(icon: ImageVector, label: String, enabled: Boolean, onClick@Composableprivate fun MenuRow(icon: ImageVector, label: String, onClick: () -> Unit) {- val ink = clear.ink- Row(Modifier.fillMaxWidth().height(44.dp).clickable(onClick = onClick).padding(horizontal = 18.dp), verticalAlignment = Alignment.CenterVertically) {- Icon(icon, null, tint = ink, modifier = Modifier.size(22.dp))- Spacer(Modifier.width(16.dp))- Text(label, color = ink, style = com.chethan616.clearpdf.ui.theme.ClearType.Body.copy(fontSize = 15.sp))+ val c = clear+ // as the desk menu's rows: the label, its glyph at the end+ Row(Modifier.fillMaxWidth().pressable(onClick).padding(horizontal = 16.dp, vertical = 11.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(label, color = c.ink, style = com.chethan616.clearpdf.ui.theme.ClearType.BodyStrong, modifier = Modifier.weight(1f))+ Icon(icon, null, tint = c.inkSoft, modifier = Modifier.size(19.dp))}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.ktindex 31d799a..1554e2e 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt@@ -229,6 +229,7 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {onScroll = { dy -> ctl.onUserScroll(dy / density.density, doc.viewer.scrollY <= 8f) },onTap = { p, at ->when {+ vm.wordEditing == doc && at != null -> vm.wordTap(doc, at)selection.selection != null -> selection.clear()ctl.tool == ViewerTool.Edit -> vm.editTap(doc, at)vm.tapField(doc, at) -> Unit@@ -427,11 +428,13 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {}// the Read Aloud player takes the bottom bar's place// while typing on the page, the bar (with its formatting) rides above the keyboard- if (vm.readAloud == null && vm.fieldActions == null) Column(Modifier.fillMaxWidth().align(Alignment.BottomCenter).then(if (vm.editing != null) Modifier.imePadding() else Modifier)) {+ if (vm.readAloud == null && vm.fieldActions == null) Column(Modifier.fillMaxWidth().align(Alignment.BottomCenter).then(if (vm.editing != null || vm.wordEditing == doc) Modifier.imePadding() else Modifier)) {vm.success?.let { SuccessBannerView(it, onClose = { vm.success = null }) }GlassBars(ctl.barsVisible && !ctl.searching && !vm.readingMode, fromTop = false) {Column(barSides) {- if (ctl.tool == ViewerTool.None) {+ if (vm.wordEditing == doc) {+ WordEditDock(vm, doc)+ } else if (ctl.tool == ViewerTool.None) {QuickToolbar(tools = QuickTool.barFor(doc, vm.quickToolbar.bar),onTool = { vm.runQuickTool(doc, it) },@@ -450,6 +453,9 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {// The active tool's sheets, over everything.ToolSheets(vm, doc)+ // Word editing: the caret and selection over the pages, and the keyboard's field+ if (vm.wordEditing == doc) WordEditLayer(vm, doc)+// Text selection's menu, and the glass lens over the text while a handle is dragged.selection.selection?.let { sel ->SelectionHandles(doc, sel)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.ktindex f991690..b395e54 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt@@ -149,8 +149,8 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {}// an office document: written by its own engine as PDF or another formatif (doc.isOffice) SheetSection {- SheetRow(LucideIcons.FileOutput, stringResource(R.string.office_export_pdf), { close(); vm.exportOffice(doc, "pdf") }, tint = Candy.Tangerine)- SheetRow(LucideIcons.Copy, stringResource(R.string.office_save_as), { ctl.sheet = ViewerSheet.SaveAs }, chevron = true, tint = Candy.Lime)+ SheetRow(LucideIcons.FilePdf, stringResource(R.string.office_export_pdf), { close(); vm.exportOffice(doc, "pdf") }, tint = Candy.Tangerine)+ SheetRow(LucideIcons.SaveAs, stringResource(R.string.office_save_as), { ctl.sheet = ViewerSheet.SaveAs }, chevron = true, tint = Candy.Lime)}if (!doc.isOffice) SheetSection {SheetRow(LucideIcons.FileOutput, stringResource(R.string.sheet_export_as), { close(); vm.openExport(doc) }, tint = Candy.Tangerine)@@ -591,7 +591,7 @@ fun SaveAsSheet(vm: AppViewModel, doc: OpenDocument) {PdfSheet(onDismiss = { ctl.sheet = ViewerSheet.None }) {SheetTitle(stringResource(R.string.office_save_as))SheetSection {- for (f in formats) SheetRow(LucideIcons.FileOutput, stringResource(R.string.office_format, formatName(f), f.uppercase()), {+ for (f in formats) SheetRow(if (f == "pdf") LucideIcons.FilePdf else LucideIcons.FileText, stringResource(R.string.office_format, formatName(f), f.uppercase()), {ctl.sheet = ViewerSheet.Nonevm.exportOffice(doc, f)}, tint = Candy.Sky)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.ktnew file mode 100644index 0000000..4962c0e--- /dev/null+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/WordEdit.kt@@ -0,0 +1,188 @@+package com.chethan616.clearpdf.ui.viewer++import androidx.compose.animation.core.RepeatMode+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.animation.core.animateFloat+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.input.key.type+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.unit.dp+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.ui.AppViewModel+import com.chethan616.clearpdf.ui.LucideIcons+import com.chethan616.clearpdf.ui.OpenDocument+import com.chethan616.clearpdf.ui.glass.GlassCircle+import com.chethan616.clearpdf.ui.glass.GlassIcon+import com.chethan616.clearpdf.ui.glass.glassBar+import com.chethan616.clearpdf.ui.glass.pressable+import com.chethan616.clearpdf.ui.theme.Candy+import com.chethan616.clearpdf.ui.theme.clear++/**+ * What the keyboard types into: a field that always holds one sentinel character. Text committed+ * after it goes into the document; the sentinel gone is a backspace. A word still being composed+ * (the keyboard's suggestions) waits until it is committed.+ */+private const val SENTINEL = ""++/**+ * Word editing over the pages: the selection's rectangles and a blinking caret, drawn where+ * WordCraft's layout puts them, and the keyboard's field.+ */+@Composable+fun WordEditLayer(vm: AppViewModel, doc: OpenDocument) {+ val caret = vm.wordCaret+ val accent = Candy.Sky+ val blink = rememberInfiniteTransition(label = "caret").animateFloat(1f, 0f, infiniteRepeatable(tween(530), RepeatMode.Reverse), label = "blink")+ Canvas(Modifier.fillMaxSize()) {+ caret ?: return@Canvas+ val v = doc.viewer+ val sel = caret.selection+ var i = 0+ while (i + 4 < sel.size) {+ val page = sel[i].toInt()+ val a = v.pageToScreen(page, sel[i + 1], sel[i + 2])+ val b = v.pageToScreen(page, sel[i + 3], sel[i + 4])+ drawRect(accent.copy(alpha = 0.25f), a, Size(b.x - a.x, b.y - a.y))+ i += 5+ }+ if (sel.isEmpty()) {+ val p = caret.page.toInt()+ val top = v.pageToScreen(p, caret.x, caret.top)+ val bottom = v.pageToScreen(p, caret.x, caret.top + caret.height)+ drawLine(accent.copy(alpha = blink.value.coerceIn(0f, 1f)), top, bottom, 2.2f * density)+ }+ }++ // the keyboard's field, out of sight+ val focus = remember { FocusRequester() }+ val keyboard = LocalSoftwareKeyboardController.current+ var field by remember { mutableStateOf(TextFieldValue(SENTINEL, TextRange(SENTINEL.length))) }+ LaunchedEffect(Unit) {+ focus.requestFocus()+ keyboard?.show()+ }+ DisposableEffect(Unit) { onDispose { keyboard?.hide() } }+ BasicTextField(+ value = field,+ onValueChange = { v ->+ if (v.composition != null) {+ field = v+ return@BasicTextField+ }+ val text = v.text+ when {+ !text.startsWith(SENTINEL) -> vm.wordRun(doc, "text.backspace")+ text.length > SENTINEL.length -> {+ // each line typed is a paragraph of its own+ val typed = text.substring(SENTINEL.length)+ typed.split('\n').forEachIndexed { n, part ->+ if (n > 0) vm.wordRun(doc, "text.newParagraph")+ if (part.isNotEmpty()) vm.wordRun(doc, "text.insert", mapOf("text" to part))+ }+ }+ }+ field = TextFieldValue(SENTINEL, TextRange(SENTINEL.length))+ },+ modifier = Modifier.size(1.dp).graphicsLayer { alpha = 0f }.focusRequester(focus).onPreviewKeyEvent { e ->+ // a hardware keyboard's Delete and Enter+ if (e.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false+ when (e.key) {+ Key.Backspace -> { vm.wordRun(doc, "text.backspace"); true }+ Key.Enter -> { vm.wordRun(doc, "text.newParagraph"); true }+ else -> false+ }+ },+ keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences, autoCorrectEnabled = true, imeAction = ImeAction.None),+ keyboardActions = KeyboardActions.Default,+ )+}++/**+ * The formatting dock while a Word document is edited: Done, undo and redo, then WordCraft's+ * Home tab: bold, italic, underline, bullets, numbering, alignment, heading, in one glass capsule.+ */+@Composable+fun WordEditDock(vm: AppViewModel, doc: OpenDocument) {+ val f = vm.wordFormat+ Row(+ Modifier.fillMaxWidth().height(BottomBarHeight).padding(horizontal = 12.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ GlassCircle(onClick = { vm.stopWordEdit() }, size = 60.dp, tint = Candy.Sky, label = stringResource(R.string.common_done)) {+ GlassIcon(LucideIcons.Check, null, Modifier.size(22.dp))+ }+ Row(+ Modifier.weight(1f).fillMaxHeight().glassBar().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ EditKey(LucideIcons.Undo2, stringResource(R.string.word_undo), doc.info.undo != null) { vm.wordRun(doc, "edit.undo") }+ EditKey(LucideIcons.Redo2, stringResource(R.string.word_redo), doc.info.redo != null) { vm.wordRun(doc, "edit.redo") }+ EditKey(LucideIcons.Bold, stringResource(R.string.word_bold), on = f.optBoolean("bold")) { vm.wordRun(doc, "format.bold") }+ EditKey(LucideIcons.Italic, stringResource(R.string.word_italic), on = f.optBoolean("italic")) { vm.wordRun(doc, "format.italic") }+ EditKey(LucideIcons.Underline, stringResource(R.string.common_tool_underline), on = f.opt("underline").let { it != null && it != false && it != "none" && it != org.json.JSONObject.NULL }) { vm.wordRun(doc, "format.underline") }+ EditKey(LucideIcons.List, stringResource(R.string.word_bullets)) { vm.wordRun(doc, "para.bullets") }+ EditKey(LucideIcons.ListOrdered, stringResource(R.string.word_numbering)) { vm.wordRun(doc, "para.numbering") }+ EditKey(LucideIcons.AlignLeft, stringResource(R.string.word_align_left)) { vm.wordRun(doc, "para.alignLeft") }+ EditKey(LucideIcons.AlignCenter, stringResource(R.string.word_align_center)) { vm.wordRun(doc, "para.alignCenter") }+ EditKey(LucideIcons.AlignRight, stringResource(R.string.word_align_right)) { vm.wordRun(doc, "para.alignRight") }+ EditKey(LucideIcons.Heading, stringResource(R.string.word_heading)) { vm.wordRun(doc, "para.style", mapOf("style" to "Heading1")) }+ EditKey(LucideIcons.Type, stringResource(R.string.word_body_text)) { vm.wordRun(doc, "para.normal") }+ }+ }+}++/** One glyph of the dock: in the glass's ink, lit by a soft accent while its formatting is on. */+@Composable+private fun EditKey(icon: ImageVector, label: String, enabled: Boolean = true, on: Boolean = false, onClick: () -> Unit) {+ val c = clear+ Box(+ Modifier.size(44.dp).pressable({ if (enabled) onClick() }).then(+ if (on) Modifier.padding(4.dp).glassBar(surface = Candy.Sky.copy(alpha = 0.28f)) else Modifier,+ ),+ contentAlignment = Alignment.Center,+ ) {+ GlassIcon(icon, label, Modifier.size(21.dp).graphicsLayer { alpha = if (enabled) 1f else 0.35f }, tint = if (on) Candy.Sky else c.ink)+ }+}diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 664829a..359e20b 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -959,6 +959,17 @@<string name="sheet_kind_word">Word</string><string name="sheet_kind_slides">Slides</string><string name="office_present">Present</string>+ <string name="word_undo">Undo</string>+ <string name="word_redo">Redo</string>+ <string name="word_bold">Bold</string>+ <string name="word_italic">Italic</string>+ <string name="word_bullets">Bullets</string>+ <string name="word_numbering">Numbering</string>+ <string name="word_align_left">Align left</string>+ <string name="word_align_center">Centre</string>+ <string name="word_align_right">Align right</string>+ <string name="word_heading">Heading</string>+ <string name="word_body_text">Body text</string><string name="office_export_pdf">Export as PDF</string><string name="office_save_as">Save as</string><string name="office_format">%1$s (.%2$s)</string>diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rsindex 7347bdc..c0e1df8 100644--- a/engine/mobile/src/lib.rs+++ b/engine/mobile/src/lib.rs@@ -32,6 +32,7 @@ mod slides;pub use photo::PhotoEditor;pub use sheets::{CellEdge, CellSpan, CellView, SheetAxes, SheetInfo};+pub use word::WordCaret;#[cfg(test)]mod tests;mod word;@@ -891,6 +892,55 @@ impl MobileSession {self.office(doc).map(|d| office::formats(d.info(doc).kind).iter().map(|f| f.to_string()).collect()).unwrap_or_default()}+ /// Save office document `doc`'s edits to absolute path `path` (its working copy), in its own format.+ pub fn save_office(&self, doc: u64, path: String) -> Result<(), MobileError> {+ self.office(doc).ok_or(MobileError::NoDocument(doc))?.save(&path)+ }++ /// Run GridCraft command `command` (JSON `params_json`, `""` = none) on `area` of sheet `sheet`+ /// of workbook `doc`, the area selected first: formatting (`home.bold`, `home.fillColor`,+ /// `home.alignCenter`, `home.percent`, ...), `cell.set`, `home.insertRows`, `edit.undo`, ...+ /// Its JSON result.+ pub fn sheet_command(&self, doc: u64, sheet: u32, area: CellSpan, command: String, params_json: String) -> Result<String, MobileError> {+ let params = if params_json.trim().is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_str(¶ms_json).map_err(|e| MobileError::Command(format!("`{command}`: the arguments are not valid JSON: {e}")))?+ };+ self.with_sheets(doc, |b| b.command(sheet, area, &command, params)).map(|v| v.to_string())+ }++ /// Run WordCraft command `command` (JSON `params_json`, `""` = none) on Word document `doc`:+ /// `caret.set {page, x, y, extend?}`, `text.insert {text}`, `text.backspace`, `text.newParagraph`,+ /// `format.bold`, `para.alignCenter`, `para.bullets`, `para.style {style}`, `edit.undo`, ...+ /// Its JSON result.+ pub fn word_command(&self, doc: u64, command: String, params_json: String) -> Result<String, MobileError> {+ let params = if params_json.trim().is_empty() {+ serde_json::json!({})+ } else {+ serde_json::from_str(¶ms_json).map_err(|e| MobileError::Command(format!("`{command}`: the arguments are not valid JSON: {e}")))?+ };+ let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;+ let w = d.as_word().ok_or(MobileError::NoDocument(doc))?;+ w.run(&command, ¶ms).map(|v| v.to_string())+ }++ /// Where Word document `doc`'s caret is, and its selection.+ pub fn word_caret(&self, doc: u64) -> Option<WordCaret> {+ self.office(doc).and_then(|d| d.as_word().and_then(|w| w.caret()))+ }++ /// Put `input` (text, a number or `=formula`) in a cell, as typing it in the formula bar does.+ pub fn sheet_set_cell(&self, doc: u64, sheet: u32, row: u32, col: u32, input: String) -> Result<(), MobileError> {+ let cell = CellSpan { row0: row, col0: col, row1: row, col1: col };+ self.with_sheets(doc, |b| b.command(sheet, cell, "cell.set", serde_json::json!({ "input": input }))).map(|_| ())+ }++ /// What the formula bar shows for a cell: its formula, else its value as typed.+ pub fn sheet_input(&self, doc: u64, sheet: u32, row: u32, col: u32) -> Result<String, MobileError> {+ self.with_sheets(doc, |b| b.input(sheet, row, col))+ }+/// The sheets of workbook `doc`, in tab order.pub fn sheets(&self, doc: u64) -> Result<Vec<SheetInfo>, MobileError> {self.with_sheets(doc, |b| Ok(b.sheets()))diff --git a/engine/mobile/src/office.rs b/engine/mobile/src/office.rsindex acae4dc..23c5a02 100644--- a/engine/mobile/src/office.rs+++ b/engine/mobile/src/office.rs@@ -37,6 +37,16 @@ pub(crate) trait OfficeDoc: Send + Sync {/// The document written as `format` (`pdf`, or one its engine writes: see [`formats`]).fn export(&self, format: &str) -> Result<Vec<u8>, MobileError>;+ /// Write the document, edits and all, to `path` in its own format (what Save does).+ fn save(&self, _path: &str) -> Result<(), MobileError> {+ Err(MobileError::Command("this document can't be edited yet, so there is nothing to save".into()))+ }++ /// A Word document, which the app edits with WordCraft's commands.+ fn as_word(&self) -> Option<&crate::word::WordDocument> {+ None+ }+/// A workbook, whose sheets the app draws as a grid of its own.fn as_sheets(&self) -> Option<&crate::sheets::SheetBook> {None@@ -56,11 +66,13 @@ pub(crate) enum OfficeFile {Word(&'static str),Slides,Sheets(&'static str),+ /// A PowerPoint 97-2003 presentation (.ppt), which no engine reads yet.+ LegacySlides,}const WORD_EXTENSIONS: &[&str] = &["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf"];const SLIDE_EXTENSIONS: &[&str] = &["pptx", "pptm", "ppsx", "ppsm", "potx", "potm"];-const SHEET_EXTENSIONS: &[&str] = &["xlsx", "xlsm", "xltx", "xltm", "xlsb", "ods", "csv", "tsv"];+const SHEET_EXTENSIONS: &[&str] = &["xlsx", "xlsm", "xltx", "xltm", "xlsb", "xls", "xlt", "ods", "csv", "tsv"];/// What the bytes of a file are, as far as office documents go, or `None` when it is not one (a/// PDF, or anything else). An encrypted package is a compound file whatever the application: its@@ -109,6 +121,14 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {if contains(&utf16("WordDocument")) {return Some(OfficeFile::Word(if word_named == Some("dot") { "dot" } else { "doc" }));}+ // Excel 97-2003: GridCraft reads its workbook stream+ if contains(&utf16("Workbook")) || (contains(&utf16("Book")) && sheets_named.is_some()) {+ return Some(OfficeFile::Sheets(if sheets_named == Some("xlt") { "xlt" } else { "xls" }));+ }+ // PowerPoint 97-2003: no reader yet, told as such rather than as a damaged file+ if contains(&utf16("PowerPoint Document")) {+ return Some(OfficeFile::LegacySlides);+ }if contains(&utf16("EncryptedPackage")) {if slides_named {return Some(OfficeFile::Slides);@@ -174,6 +194,11 @@ pub(crate) fn open(OfficeFile::Word(ext) => Arc::new(crate::word::WordDocument::open(path, ext, bytes, password, locale)?),OfficeFile::Slides => Arc::new(crate::slides::SlideDeck::open(path, bytes)?),OfficeFile::Sheets(ext) => Arc::new(crate::sheets::SheetBook::open(path, ext, bytes, password)?),+ OfficeFile::LegacySlides => {+ return Err(MobileError::Open(+ "This is a PowerPoint 97-2003 presentation (.ppt), which Artefact can't open yet. Saved as .pptx (PowerPoint, Keynote, Google Slides or LibreOffice can), it opens here.".into(),+ ));+ }})}@@ -256,6 +281,13 @@ mod tests {assert_eq!(sniff(&cfb, "/a/Locked.pptx"), Some(OfficeFile::Slides));assert_eq!(sniff(&cfb, "/a/Locked.xlsx"), Some(OfficeFile::Sheets("xlsx")));assert_eq!(sniff(&cfb, "/a/Locked.bin"), None);+ let legacy = |stream: &str| {+ let mut b = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];+ b.extend(stream.encode_utf16().flat_map(u16::to_le_bytes));+ b+ };+ assert_eq!(sniff(&legacy("Workbook"), "/a/Old.xls"), Some(OfficeFile::Sheets("xls")));+ assert_eq!(sniff(&legacy("PowerPoint Document"), "/a/Old.ppt"), Some(OfficeFile::LegacySlides));}#[test]diff --git a/engine/mobile/src/sheets.rs b/engine/mobile/src/sheets.rsindex f40b662..8e511ae 100644--- a/engine/mobile/src/sheets.rs+++ b/engine/mobile/src/sheets.rs@@ -3,7 +3,7 @@//! cells of a window with their looks, column widths and row heights, merges, frozen panes). Its//! sheets still count as the document's pages, for titles, Recent and thumbnails.-use std::sync::Arc;+use std::sync::{Arc, Mutex, MutexGuard, PoisonError};use gridcraft_engine::core::CellRef;use gridcraft_engine::model::{BorderLine, BorderStyle, Color, HAlign, PatternType, Sheet, VAlign, Visibility, Workbook};@@ -82,9 +82,9 @@ pub struct CellSpan {pub col1: u32,}-/// One open workbook, its formulas computed.+/// One open workbook, held by GridCraft's session (its formulas computed, its edits undoable).pub(crate) struct SheetBook {- wb: Arc<Workbook>,+ session: Mutex<gridcraft_engine::Session>,name: String,path: String,file_size: u64,@@ -110,17 +110,69 @@ impl SheetBook {let name = crate::office::file_name(path);let stem = std::path::Path::new(&name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();let encrypted = gridcraft_xlsx::sniff(bytes) == gridcraft_xlsx::Format::Encrypted;- let (mut wb, _warnings) =+ let (wb, _warnings) =gridcraft_engine::io::open_bytes_with_password(&format!("{stem}.{ext}"), bytes, password).map_err(|e| open_error(e.to_string()))?;- // computed as the desktop app does on open: values the file left stale are brought up to date- gridcraft_engine::calc::Calc::new().recalc_all(&mut wb);- Ok(SheetBook { wb: Arc::new(wb), name, path: path.to_string(), file_size: bytes.len() as u64, encrypted })+ // the desktop app's document: computed on open (values the file left stale are brought up to+ // date), with its selection and undo history+ let mut session = gridcraft_engine::Session::new();+ let doc = gridcraft_engine::DocState::new(wb, Some(path.to_string()), stem, gridcraft_engine::Trust::FromFile);+ let i = session.add_document(doc);+ session.set_active(i);+ Ok(SheetBook { session: Mutex::new(session), name, path: path.to_string(), file_size: bytes.len() as u64, encrypted })}- fn sheet(&self, index: u32) -> Result<&Sheet, MobileError> {- let n = self.wb.sheets.len();- self.wb- .sheets+ fn lock(&self) -> MutexGuard<'_, gridcraft_engine::Session> {+ self.session.lock().unwrap_or_else(PoisonError::into_inner)+ }++ /// The workbook as it is now (shared: reading it never holds the session).+ fn wb(&self) -> Arc<Workbook> {+ self.lock().active().map(|d| d.wb.clone()).unwrap_or_default()+ }++ /// Run GridCraft command `command` with `params` on the cells of `area` on sheet `sheet` (they+ /// are selected first, as a tap selects them in the app): the Home tab's formatting, `cell.set`,+ /// inserting and deleting rows and columns, `edit.undo` and `edit.redo`, and the rest.+ pub(crate) fn command(&self, sheet: u32, area: CellSpan, command: &str, params: serde_json::Value) -> Result<serde_json::Value, MobileError> {+ let name = self.sheet(sheet)?.name.clone();+ let range = gridcraft_engine::core::RangeRef::new(CellRef::new(area.row0, area.col0), CellRef::new(area.row1, area.col1));+ let mut s = self.lock();+ let err = |e: gridcraft_engine::EngineError| MobileError::Command(e.to_string());+ s.execute("sheet.activate", serde_json::json!({ "sheet": name })).map_err(err)?;+ s.execute("selection.set", serde_json::json!({ "range": range.a1(), "active": range.start.a1() })).map_err(err)?;+ s.execute(command, params).map_err(err)+ }++ /// What the formula bar shows for a cell: its formula (`=SUM(A1:A3)`), else its value as typed.+ pub(crate) fn input(&self, sheet: u32, row: u32, col: u32) -> Result<String, MobileError> {+ let wb = self.wb();+ let s = self.sheet_in(&wb, sheet)?;+ let c = CellRef::new(row, col);+ if let Some(f) = s.cell(c).and_then(|x| x.formula.as_ref()) {+ return Ok(format!("={}", f.text));+ }+ Ok(gridcraft_engine::display::value_text(&wb, s, c))+ }++ /// Write the workbook to `path` in the format its name says (.xlsx, .xls, .ods, .csv, ...): a save.+ pub(crate) fn save_to(&self, path: &str) -> Result<(), MobileError> {+ let mut s = self.lock();+ let d = s.active_mut().ok_or_else(|| MobileError::Command("no workbook".into()))?;+ let bytes = gridcraft_engine::io::save_bytes(&d.wb, path).map_err(|e| MobileError::Command(e.to_string()))?;+ std::fs::write(path, bytes).map_err(|e| MobileError::Command(format!("{path}: {e}")))?;+ d.saved = d.wb.clone();+ Ok(())+ }++ fn sheet(&self, index: u32) -> Result<Arc<Sheet>, MobileError> {+ let wb = self.wb();+ self.sheet_in(&wb, index)?;+ wb.sheets.get(index as usize).cloned().ok_or(MobileError::NoDocument(0))+ }++ fn sheet_in<'a>(&self, wb: &'a Workbook, index: u32) -> Result<&'a Sheet, MobileError> {+ let n = wb.sheets.len();+ wb.sheets.get(index as usize).map(|s| &**s).ok_or_else(|| MobileError::Command(format!("sheet {} is out of range: the workbook has {n} sheets", u64::from(index) + 1)))@@ -128,8 +180,8 @@ impl SheetBook {/// The sheets in tab order.pub(crate) fn sheets(&self) -> Vec<SheetInfo> {- self.wb- .sheets+ let wb = self.wb();+ wb.sheets.iter().map(|s| {let (rows, cols) = s.used_range().map_or((0, 0), |r| (r.end.row.saturating_add(1), r.end.col.saturating_add(1)));@@ -141,7 +193,7 @@ impl SheetBook {frozen_cols: s.freeze.map_or(0, |f| f.1),gridlines: s.show_gridlines,hidden: s.visibility != Visibility::Visible,- tab_color: s.tab_color.and_then(|c| rgb(c.resolve(&self.wb.theme))),+ tab_color: s.tab_color.and_then(|c| rgb(c.resolve(&wb.theme))),}}).collect()@@ -149,7 +201,8 @@ impl SheetBook {/// Widths of columns `col0..col0+cols` and heights of rows `row0..row0+rows` of sheet `sheet`.pub(crate) fn axes(&self, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<SheetAxes, MobileError> {- let s = self.sheet(sheet)?;+ let wb = self.wb();+ let s = self.sheet_in(&wb, sheet)?;let cols = cols.min(16_384);let rows = rows.min(1_048_576).min(100_000);Ok(SheetAxes {@@ -160,11 +213,12 @@ impl SheetBook {/// The cells of the window that show something (text, a fill or a border).pub(crate) fn cells(&self, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<Vec<CellView>, MobileError> {- let s = self.sheet(sheet)?;+ let book = self.wb();+ let s = self.sheet_in(&book, sheet)?;if u64::from(rows) * u64::from(cols) > MAX_WINDOW {return Err(MobileError::Command(format!("a window of {rows} × {cols} cells is too large")));}- let wb = &*self.wb;+ let wb = &*book;let theme = &wb.theme;let edge = |b: &BorderLine| CellEdge {weight: match b.style {@@ -233,12 +287,19 @@ impl SheetBook {/// The merged areas of sheet `sheet`.pub(crate) fn merges(&self, sheet: u32) -> Result<Vec<CellSpan>, MobileError> {- Ok(self.sheet(sheet)?.merges.iter().map(|m| CellSpan { row0: m.start.row, col0: m.start.col, row1: m.end.row, col1: m.end.col }).collect())+ let wb = self.wb();+ Ok(self+ .sheet_in(&wb, sheet)?+ .merges+ .iter()+ .map(|m| CellSpan { row0: m.start.row, col0: m.start.col, row1: m.end.row, col1: m.end.col })+ .collect())}/// The cells of sheet `sheet` whose shown text holds `query` (at most `limit`), in reading order.pub(crate) fn find(&self, sheet: u32, query: &str, case_sensitive: bool, limit: u32) -> Result<Vec<CellSpan>, MobileError> {- let s = self.sheet(sheet)?;+ let wb = self.wb();+ let s = self.sheet_in(&wb, sheet)?;let q = if case_sensitive { query.to_string() } else { query.to_lowercase() };if q.trim().is_empty() {return Ok(Vec::new());@@ -247,7 +308,7 @@ impl SheetBook {let mut out = Vec::new();for row in 0..=used.end.row {for col in 0..=used.end.col {- let t = gridcraft_engine::display::cell_text(&self.wb, s, CellRef::new(row, col));+ let t = gridcraft_engine::display::cell_text(&wb, s, CellRef::new(row, col));let hit = if case_sensitive { t.contains(&q) } else { t.to_lowercase().contains(&q) };if hit {out.push(CellSpan { row0: row, col0: col, row1: row, col1: col });@@ -271,7 +332,17 @@ impl SheetBook {impl OfficeDoc for SheetBook {fn info(&self, id: u64) -> DocumentInfo {- let p = &self.wb;+ let (p, dirty, generation, undo, redo) = {+ let s = self.lock();+ let d = s.active();+ (+ d.map(|d| d.wb.clone()).unwrap_or_default(),+ d.is_some_and(|d| d.is_dirty()),+ d.map_or(0, |d| d.revision),+ d.and_then(|d| d.undo.last()).map(|h| h.label.clone()),+ d.and_then(|d| d.redo.last()).map(|h| h.label.clone()),+ )+ };DocumentInfo {id,kind: DocumentKind::Sheets,@@ -295,21 +366,21 @@ impl OfficeDoc for SheetBook {file_size: self.file_size,encrypted: self.encrypted,tagged: false,- read_only_reason: Some("Workbooks open for viewing in this version".into()),+ read_only_reason: None,allows_printing: true,allows_copying: true,allows_annotation: false,allows_form_filling: false,allows_assembly: false,- dirty: false,- undo: None,- redo: None,+ dirty,+ undo,+ redo,fields: 0,has_outline: false,attachments: 0,signed: false,comments_hidden: false,- generation: 0,+ generation,}}@@ -317,6 +388,7 @@ impl OfficeDoc for SheetBook {/// the real grid itself).fn render_page(&self, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError> {let s = self.sheet(page)?;+ let s = &*s;let (w, h) = Self::extent(s);let scale = scale.clamp(0.01, 4.0);let (full_w, full_h) = (((w * scale).ceil() as u32).clamp(1, 2048), ((h * scale).ceil() as u32).clamp(1, 2048));@@ -393,16 +465,13 @@ impl OfficeDoc for SheetBook {match format {"pdf" => {// the engine's own export: each sheet's page setup, every visible sheet- let mut s = gridcraft_engine::Session::new();- let doc = gridcraft_engine::DocState::new((*self.wb).clone(), None, self.name.clone(), gridcraft_engine::Trust::FromFile);- let i = s.add_document(doc);- s.set_active(i);- let out = s.execute("file.exportPdf", serde_json::json!({ "sheets": "all" })).map_err(|e| MobileError::Command(e.to_string()))?;+ let out =+ self.lock().execute("file.exportPdf", serde_json::json!({ "sheets": "all" })).map_err(|e| MobileError::Command(e.to_string()))?;let b64 = out.get("base64").and_then(serde_json::Value::as_str).unwrap_or_default();gridcraft_engine::io::base64_decode(b64).ok_or_else(|| MobileError::Command("the workbook could not be written as PDF".into()))}"xlsx" | "csv" => {- gridcraft_engine::io::save_bytes(&self.wb, &format!("workbook.{format}")).map_err(|e| MobileError::Command(e.to_string()))+ gridcraft_engine::io::save_bytes(&self.wb(), &format!("workbook.{format}")).map_err(|e| MobileError::Command(e.to_string()))}_ => Err(crate::office::unknown_format(DocumentKind::Sheets, format)),}@@ -411,4 +480,8 @@ impl OfficeDoc for SheetBook {fn as_sheets(&self) -> Option<&SheetBook> {Some(self)}++ fn save(&self, path: &str) -> Result<(), MobileError> {+ self.save_to(path)+ }}diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rsindex 7710742..19ab954 100644--- a/engine/mobile/src/tests.rs+++ b/engine/mobile/src/tests.rs@@ -462,7 +462,7 @@ fn opens_a_word_document_beside_the_pdfs() {assert_eq!(word.name, "Report.docx");assert_eq!(word.pages.len(), 1);assert!(word.pages[0].width > 500.0 && word.pages[0].height > 700.0, "{:?}", word.pages[0]);- assert!(word.read_only_reason.is_some());+ assert!(word.read_only_reason.is_none(), "Word documents are editable");assert_eq!(s.documents(), vec![pdf.id, word.id]);assert_eq!(s.document(word.id).unwrap().pages.len(), 1);// the PDF-only lists are empty, not errors@@ -654,3 +654,61 @@ fn office_documents_export_to_pdf_and_their_own_formats() {assert!(s.export_office(id, "exe".into(), dir.join("x").to_string_lossy().into_owned()).is_err());}}++#[test]+fn a_workbook_is_edited_recalculated_undone_and_saved() {+ let s = MobileSession::new();+ let path = book_file("Item,Price\nApples,3\nPears,4\n", "Edit.xlsx");+ let id = s.open(path.clone(), None).unwrap().id;+ let text = |r: u32, c: u32| s.sheet_cells(id, 0, 0, 10, 0, 5).unwrap().into_iter().find(|x| x.row == r && x.col == c).map(|x| x.text);+ s.sheet_set_cell(id, 0, 3, 1, "=SUM(B2:B3)".into()).unwrap();+ assert_eq!(text(3, 1).as_deref(), Some("7"));+ assert_eq!(s.sheet_input(id, 0, 3, 1).unwrap(), "=SUM(B2:B3)");+ // a changed input recalculates what depends on it+ s.sheet_set_cell(id, 0, 1, 1, "10".into()).unwrap();+ assert_eq!(text(3, 1).as_deref(), Some("14"));+ let b2 = CellSpan { row0: 1, col0: 1, row1: 1, col1: 1 };+ s.sheet_command(id, 0, b2, "home.bold".into(), String::new()).unwrap();+ assert!(s.sheet_cells(id, 0, 1, 1, 1, 1).unwrap()[0].bold);+ let info = s.document(id).unwrap();+ assert!(info.dirty && info.undo.is_some());+ s.sheet_command(id, 0, b2, "edit.undo".into(), String::new()).unwrap();+ assert!(!s.sheet_cells(id, 0, 1, 1, 1, 1).unwrap()[0].bold);+ s.save_office(id, path.clone()).unwrap();+ assert!(!s.document(id).unwrap().dirty);+ let again = s.open(path, None).unwrap().id;+ assert_eq!(s.sheet_input(again, 0, 3, 1).unwrap(), "=SUM(B2:B3)");+ assert!(s.sheet_command(id, 0, b2, "no.such.command".into(), String::new()).is_err());+}++#[test]+fn a_word_document_is_typed_in_formatted_undone_and_saved() {+ let s = MobileSession::new();+ let path = word_file("Hello world", "Typing.docx");+ let id = s.open(path.clone(), None).unwrap().id;+ let before = s.document(id).unwrap().generation;+ // a tap at the end of the line puts the caret there; typing goes in where it is+ let hits = s.find_in_page(id, 0, "world".into(), false, false).unwrap();+ let r = &hits[0].rects;+ s.word_command(id, "caret.set".into(), format!(r#"{{"page":0,"x":{},"y":{}}}"#, r[2] + 1.0, (r[1] + r[3]) / 2.0)).unwrap();+ let caret = s.word_caret(id).unwrap();+ assert_eq!(caret.page, 0);+ assert!(caret.height > 4.0 && caret.selection.is_empty());+ s.word_command(id, "text.insert".into(), r#"{"text":", again"}"#.into()).unwrap();+ assert_eq!(s.page_plain_text(id, 0).unwrap().trim(), "Hello world, again");+ let info = s.document(id).unwrap();+ assert!(info.dirty && info.undo.is_some() && info.generation != before);+ // select all and make it bold: the selection has rectangles+ s.word_command(id, "select.all".into(), String::new()).unwrap();+ assert!(!s.word_caret(id).unwrap().selection.is_empty());+ s.word_command(id, "format.bold".into(), String::new()).unwrap();+ s.word_command(id, "edit.undo".into(), String::new()).unwrap();+ s.word_command(id, "edit.undo".into(), String::new()).unwrap();+ assert_eq!(s.page_plain_text(id, 0).unwrap().trim(), "Hello world");+ s.word_command(id, "edit.redo".into(), String::new()).unwrap();+ s.save_office(id, path.clone()).unwrap();+ assert!(!s.document(id).unwrap().dirty);+ let again = s.open(path, None).unwrap().id;+ assert_eq!(s.page_plain_text(again, 0).unwrap().trim(), "Hello world, again");+ assert!(s.word_command(id, "no.such.command".into(), String::new()).is_err());+}diff --git a/engine/mobile/src/word.rs b/engine/mobile/src/word.rsindex a2049a2..f110c3a 100644--- a/engine/mobile/src/word.rs+++ b/engine/mobile/src/word.rs@@ -16,6 +16,22 @@ use wordcraft_engine::render::RenderOptions;use crate::office::{ASCENT, DESCENT, OfficeDoc, is_web_link, text_glyph};use crate::{DocumentInfo, DocumentKind, LinkInfo, MobileError, PageInfo, RenderedImage, TileRect};+/// Where the caret is on a page (points), and the selection's rectangles when there is one.+#[derive(Debug, Clone, uniffi::Record)]+pub struct WordCaret {+ pub page: u32,+ pub x: f32,+ pub top: f32,+ pub height: f32,+ /// The selected text's rectangles, five numbers each: page, x0, y0, x1, y1 (empty for a caret).+ pub selection: Vec<f32>,+}++/// Commands that only move the caret or read: the document's version stays.+fn changes_nothing(command: &str) -> bool {+ command.starts_with("caret.") || command.starts_with("select.") || command == "format.state" || command == "list.get"+}+/// One open Word document: the engine's session (document, layout, history) and its text layers.pub(crate) struct WordDocument {state: Mutex<WordState>,@@ -88,6 +104,37 @@ impl WordDocument {}}+impl WordDocument {+ /// Run WordCraft command `command` with `params` (`text.insert {text}`, `format.bold`,+ /// `para.alignCenter`, `caret.set {page, x, y}`, `edit.undo`, ...); its JSON result.+ pub(crate) fn run(&self, command: &str, params: &serde_json::Value) -> Result<serde_json::Value, MobileError> {+ let mut s = self.lock();+ let out = s.session.run(command, params).map_err(|e| MobileError::Command(e.to_string()))?;+ if !changes_nothing(command) {+ s.generation = s.generation.wrapping_add(1);+ }+ Ok(out)+ }++ /// The caret (or the selection) as it is drawn.+ pub(crate) fn caret(&self) -> Option<WordCaret> {+ let mut s = self.lock();+ let layout = s.session.layout();+ let sel = s.session.sel.clone();+ let c = layout.caret(&sel.focus)?;+ let selection = if sel.anchor == sel.focus {+ Vec::new()+ } else {+ layout+ .selection_rects(&s.session.doc, &sel.anchor, &sel.focus, c.page)+ .into_iter()+ .flat_map(|(page, r)| [page as f32, r.x, r.y, r.x + r.w, r.y + r.h])+ .collect()+ };+ Some(WordCaret { page: u32::try_from(c.page).unwrap_or(u32::MAX), x: c.x, top: c.top, height: c.height, selection })+ }+}+impl OfficeDoc for WordDocument {fn info(&self, id: u64) -> DocumentInfo {let (doc, layout, generation) = self.snapshot();@@ -109,15 +156,15 @@ impl OfficeDoc for WordDocument {file_size: s.file_size,encrypted: s.encrypted,tagged: false,- read_only_reason: Some("Word documents open for reading in this version".into()),+ read_only_reason: None,allows_printing: true,allows_copying: true,allows_annotation: false,allows_form_filling: false,allows_assembly: false,dirty: s.session.dirty,- undo: None,- redo: None,+ undo: s.session.undo_label().map(str::to_string),+ redo: s.session.redo_label().map(str::to_string),fields: 0,has_outline: false,attachments: 0,@@ -179,6 +226,19 @@ impl OfficeDoc for WordDocument {wordcraft_engine::io::save_bytes(&format!("document.{format}"), &s.session.doc).map_err(MobileError::Command)}+ fn save(&self, path: &str) -> Result<(), MobileError> {+ let mut s = self.lock();+ let password = s.session.password.as_ref().map(|p| p.as_str().to_string());+ let opts = wordcraft_engine::io::ExportOptions::default();+ wordcraft_engine::io::save_path_with(std::path::Path::new(path), &s.session.doc, password.as_deref(), &opts).map_err(MobileError::Command)?;+ s.session.dirty = false;+ Ok(())+ }++ fn as_word(&self) -> Option<&WordDocument> {+ Some(self)+ }+/// The text layers go; they are built again when needed.fn release_memory(&self) {*self.texts.lock().unwrap_or_else(PoisonError::into_inner) = (0, Vec::new());