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
Office documents get their own tools; one thought of the day; files by kind; a smooth way in from Quick Preview
chethan6168ecd27826848
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex fa56d78..14ad8f4 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -64,6 +64,8 @@<data android:mimeType="application/vnd.oasis.opendocument.spreadsheet" /><data android:mimeType="text/csv" /><data android:mimeType="text/comma-separated-values" />+ <data android:mimeType="text/plain" />+ <data android:mimeType="text/markdown" /></intent-filter></activity>@@ -109,6 +111,8 @@<data android:mimeType="application/vnd.oasis.opendocument.spreadsheet" /><data android:mimeType="text/csv" /><data android:mimeType="text/comma-separated-values" />+ <data android:mimeType="text/plain" />+ <data android:mimeType="text/markdown" /></intent-filter></activity>diff --git a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.ktindex 022cf0f..5b76a2f 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/MainActivity.kt@@ -197,9 +197,10 @@ class MainActivity : ComponentActivity() {}// from Quick Preview: its own copy when Android didn't pass the original onval local = intent?.getStringExtra(EXTRA_LOCAL_COPY)?.let(::File)?.takeIf { it.isFile && it.canonicalPath.startsWith(filesDir.canonicalPath) }+ val fromPreview = intent?.getBooleanExtra(EXTRA_FROM_PREVIEW, false) == truewhen {- uri != null -> vm.open(uri, fromOtherApp = true)- local != null -> vm.open(Uri.fromFile(local), fromOtherApp = true)+ uri != null -> vm.open(uri, fromOtherApp = true, copy = local, fromPreview = fromPreview)+ local != null -> vm.open(Uri.fromFile(local), fromOtherApp = true, fromPreview = fromPreview)}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.ktindex 97fe1f1..e0136a6 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt@@ -40,23 +40,46 @@ object DocumentTypes {"text/tab-separated-values",)+ /** Plain text and Markdown, read by the Word engine. */+ val TEXT = arrayOf("text/plain", "text/markdown", "text/x-markdown")+/** Everything the viewer opens. */- val OPENABLE = arrayOf(PDF) + WORD + SLIDES + SHEETS+ val OPENABLE = arrayOf(PDF) + WORD + SLIDES + SHEETS + TEXTprivate val WORD_EXTENSIONS = setOf("docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf")private val SLIDE_EXTENSIONS = setOf("pptx", "pptm", "ppsx", "ppsm", "potx", "potm")private val SHEET_EXTENSIONS = setOf("xlsx", "xlsm", "xltx", "xltm", "xlsb", "ods", "csv", "tsv")+ private val TEXT_EXTENSIONS = setOf("txt", "md", "markdown")++ /** The kinds a file list can be narrowed to (Files ▸ ⋯). */+ enum class Kind(val label: Int, val icon: androidx.compose.ui.graphics.vector.ImageVector) {+ All(com.chethan616.clearpdf.R.string.files_kind_all, com.chethan616.clearpdf.ui.LucideIcons.Files),+ Pdf(com.chethan616.clearpdf.R.string.files_kind_pdf, com.chethan616.clearpdf.ui.LucideIcons.FileText),+ Word(com.chethan616.clearpdf.R.string.files_kind_word, com.chethan616.clearpdf.ui.LucideIcons.FilePenLine),+ Slides(com.chethan616.clearpdf.R.string.files_kind_slides, com.chethan616.clearpdf.ui.LucideIcons.Presentation),+ Sheets(com.chethan616.clearpdf.R.string.files_kind_sheets, com.chethan616.clearpdf.ui.LucideIcons.Sheet),+ Text(com.chethan616.clearpdf.R.string.files_kind_text, com.chethan616.clearpdf.ui.LucideIcons.Type),+ }++ /** The kind a file named [name] is. */+ fun kindOf(name: String): Kind = when (extension(name)) {+ in WORD_EXTENSIONS -> Kind.Word+ in SLIDE_EXTENSIONS -> Kind.Slides+ in SHEET_EXTENSIONS -> Kind.Sheets+ in TEXT_EXTENSIONS -> Kind.Text+ else -> Kind.Pdf+ }private fun extension(name: String) = name.substringAfterLast('.', "").lowercase()fun isWordName(name: String) = extension(name) in WORD_EXTENSIONS/** An office document's name (Word, slides or a workbook): it keeps its own extension. */- fun isOfficeName(name: String) = extension(name).let { it in WORD_EXTENSIONS || it in SLIDE_EXTENSIONS || it in SHEET_EXTENSIONS }+ fun isOfficeName(name: String) = extension(name).let { it in WORD_EXTENSIONS || it in SLIDE_EXTENSIONS || it in SHEET_EXTENSIONS || it in TEXT_EXTENSIONS }/** Whether a file of type [mime] named [name] is one the viewer opens. */fun isOpenable(mime: String?, name: String) =- mime == PDF || mime in WORD || mime in SLIDES || mime in SHEETS || extension(name) == "pdf" || isOfficeName(name)+ mime == PDF || mime in WORD || mime in SLIDES || mime in SHEETS || mime in TEXT || extension(name) == "pdf" || isOfficeName(name)/** A file name without its extension, as documents are titled (`Report.docx` → `Report`). */fun title(name: String): String =@@ -79,6 +102,8 @@ object DocumentTypes {"ods" -> SHEETS[4]"csv" -> "text/csv""tsv" -> "text/tab-separated-values"+ "txt" -> "text/plain"+ "md", "markdown" -> "text/markdown"else -> PDF}}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 7c044f2..fe5fe1b 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,9 @@ object LucideIcons {val FilePlus2: ImageVector get() = Icons.AutoMirrored.Rounded.NoteAddval FileStack: ImageVector get() = Icons.Rounded.FileCopyval FileText: ImageVector get() = Icons.Rounded.Description+ val Files: ImageVector get() = Icons.Rounded.FileCopy+ val Presentation: ImageVector get() = Icons.Rounded.Slideshow+ val Sheet: ImageVector get() = Icons.Rounded.TableChartval FolderOpen: ImageVector get() = Icons.Rounded.FolderOpenval FolderPlus: ImageVector get() = Icons.Rounded.CreateNewFolderval GalleryVerticalEnd: ImageVector get() = Icons.Rounded.ViewDaydiff --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 3684aff..982d59f 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@@ -134,8 +134,10 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr* [fromOtherApp]: another app opened it, so closing it goes back to that app rather than Home,* as the reference does (#47).*/- fun open(uri: Uri, password: String? = null, fromOtherApp: Boolean = false) {+ fun open(uri: Uri, password: String? = null, fromOtherApp: Boolean = false, copy: File? = null, fromPreview: Boolean = false) {otherAppUri = uri.takeIf { fromOtherApp }+ // from Quick Preview the desk never shows: a plain ground until the document rises over it+ if (fromPreview) expandingPreview = true// a file opened from another app comes to the front, not under SettingssettingsOpen = falseshowLicences = false@@ -145,7 +147,8 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrtry {val file = withContext(Dispatchers.IO) {files.keepAccess(uri)- files.workingCopy(uri)+ // Quick Preview has just copied it in: no second copy of the same bytes+ copy ?: files.workingCopy(uri)}openFile(eng, uri, file, password)} catch (e: java.io.FileNotFoundException) {@@ -177,10 +180,15 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrtell(e.userMessage)} finally {opening = false+ // a document that didn't open (or asked for its password) shows the desk after all+ if (document == null) expandingPreview = false}}}+ /** Opening a document from Quick Preview: the desk stays hidden until the document covers it. */+ var expandingPreview by mutableStateOf(false)+/** The password dialog's answer: try again with [password], or give up (null). */fun answerPassword(password: String?) {val req = passwordRequest ?: return@@ -598,6 +606,15 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrreturn}viewModelScope.launch {+ // an office document prints as the PDF its engine writes+ if (doc.isOffice) {+ val eng = engine ?: return@launch+ val out = tempFile("pdf")+ runCatching { eng.command { exportOffice(doc.id, "pdf", out.absolutePath) } }+ .onSuccess { prints.trySend(out to "${doc.title}.pdf") }+ .onFailure { tell(it.userMessage) }+ return@launch+ }save(doc)// the system's printing can't open a password-protected file: print an unlocked copyval file = if (doc.info.encrypted) unlockedCopy(doc) ?: doc.file else doc.file@@ -2381,6 +2398,24 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr/** The note open in the editor. */var openNote by mutableStateOf<String?>(null)+ /** A presentation shown full screen, slide by slide. */+ var presenting by mutableStateOf<OpenDocument?>(null)++ /**+ * Write office document [doc] as [format] (`pdf`, `docx`, …) with its own engine and save it to+ * Downloads, offering to open it.+ */+ fun exportOffice(doc: OpenDocument, format: String) {+ val eng = engine ?: return+ viewModelScope.launch {+ val out = tempFile(format)+ val name = "${doc.title}.$format"+ runCatching { eng.command { exportOffice(doc.id, format, out.absolutePath) } }+ .onSuccess { deliver(out, name, DocumentTypes.mimeOf(name)) }+ .onFailure { tell(it.userMessage) }+ }+ }+/** A note's picture being edited (note id, picture name), over everything. */var editingPhoto by mutableStateOf<Pair<String, String>?>(null)@@ -3013,6 +3048,19 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr// Last in the class: initializers and init blocks run in source order, and this coroutine can run// straight away (a started engine) or on another thread, so every property must exist first.init {+ // a past day's thought that was only read, never written on, leaves the desk (it showed as a+ // second "Thought of the day"); one written on stays as the note it became+ viewModelScope.launch {+ snapshotFlow { notes.loaded }.first { it }+ val res = getApplication<Application>().resources+ val today = com.chethan616.clearpdf.notes.today()+ val heading = text(R.string.thought_title)+ notes.all.filter { it.thought != 0L && it.thought != today }.forEach { n ->+ val seed = com.chethan616.clearpdf.notes.thoughtFor(res, n.thought)+ val untouched = (n.title == seed.quote && n.body == seed.reflection) || n.title == heading || (n.title.isBlank() && n.body.isBlank())+ if (untouched && n.images.isEmpty() && n.audio == null) notes.delete(n.id)+ }+ }viewModelScope.launch {application.engine.await().onSuccess { engine = it }.onFailure { engineProblem = it.userMessage }refreshRecents()diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.ktindex 0673474..9460927 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt@@ -43,6 +43,7 @@ import androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.snapshotFlow+import kotlinx.coroutines.flow.firstimport androidx.compose.runtime.SideEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.key@@ -184,7 +185,8 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:snapshotFlow { reveal.progress.value.let { it <= 0f || it >= 1f } }.collect { vm.deskStill = it }}// under an open document nothing of the desk shows: skip drawing it (and its glass) entirely- val underDoc = Modifier.drawWithContent { if (!reveal.covering) drawContent() }+ // (nor while a document from Quick Preview opens: the desk is never seen on that way in)+ val underDoc = Modifier.drawWithContent { if (!reveal.covering && !vm.expandingPreview) drawContent() }GlassStage(wallpaper = { Aurora(mood, underDoc) },screens = {@@ -200,6 +202,17 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:}}}+ // from Quick Preview: the viewer's own ground instead of the desk while the document opens,+ // so the window comes in on one quiet colour and the document rises as it does from the desk+ if (vm.expandingPreview) {+ Box(Modifier.fillMaxSize().background(pdfColors.desk))+ LaunchedEffect(Unit) {+ // the card sat at the bottom of the screen: the document grows from there+ LastTouch.x = Float.NaN+ snapshotFlow { reveal.covering }.first { it }+ vm.expandingPreview = false+ }+ }// the document rises over the desk (translation and a cheap fade: no scaling, no layer)Reveal(doc, reveal) { Viewer(vm, it) }// a tool's own screen opens over whatever it was started from: the desk or a document@@ -207,6 +220,7 @@ private fun Shell(vm: AppViewModel, onBrowse: () -> Unit, onPickSignatureImage:vm.toolScreen?.let { ToolScreenHost(vm, it) }vm.signaturePad?.let { SignaturePadScreen(vm, it, onPickSignatureImage) }vm.certSign?.let { CertSignScreen(vm, it) }+ vm.presenting?.let { d -> com.chethan616.clearpdf.ui.viewer.PresentMode(vm, d) { vm.presenting = null } }vm.editingPhoto?.let { (note, picture) -> com.chethan616.clearpdf.ui.notes.PhotoEditScreen(vm, note, picture) { vm.editingPhoto = null } }if (vm.idCreate) CreateIdScreen(vm)}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.ktindex 8cb22e1..3c89e9e 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/FilesScreen.kt@@ -82,6 +82,8 @@ fun FilesScreen(vm: AppViewModel, onBrowse: () -> Unit) {var tab by rememberSaveable { mutableIntStateOf(0) }var query by rememberSaveable { mutableStateOf("") }var sortByName by rememberSaveable { mutableStateOf(false) }+ // narrowed to one kind of file from the ⋯ menu+ var kind by rememberSaveable { mutableStateOf(com.chethan616.clearpdf.engine.DocumentTypes.Kind.All) }var menuAnchor by remember { mutableStateOf<Rect?>(null) }var menuOpen by remember { mutableStateOf(false) }var confirmClear by remember { mutableStateOf(false) }@@ -102,6 +104,7 @@ fun FilesScreen(vm: AppViewModel, onBrowse: () -> Unit) {tab == 1 -> vm.starredRows()else -> vm.localRows()}.let { if (sortByName && query.isBlank()) it.sortedBy { r -> r.name.lowercase() } else it }+ .let { if (kind == com.chethan616.clearpdf.engine.DocumentTypes.Kind.All) it else it.filter { r -> com.chethan616.clearpdf.engine.DocumentTypes.kindOf(r.name) == kind } }// a search left alone for a moment counts as one madeLaunchedEffect(query) {@@ -189,6 +192,10 @@ fun FilesScreen(vm: AppViewModel, onBrowse: () -> Unit) {val anchor = menuAnchor ?: Rect.Zeroval items = buildList {add(GlassMenuItem(stringResource(if (sortByName) R.string.home_sort_by_date else R.string.home_sort_by_name), LucideIcons.ArrowUpDown) { sortByName = !sortByName })+ // show one kind of file: the one shown has a tick+ for (k in com.chethan616.clearpdf.engine.DocumentTypes.Kind.entries) {+ add(GlassMenuItem(stringResource(k.label), if (k == kind) LucideIcons.Check else k.icon) { kind = k })+ }if (tab == 0 && vm.recentList.isNotEmpty()) add(GlassMenuItem(stringResource(R.string.home_clear_recent), LucideIcons.BrushCleaning) { confirmClear = true })if (tab == 2) {add(GlassMenuItem(stringResource(R.string.home_refresh), LucideIcons.RotateCw) { vm.scanLocal(force = true) })diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.ktindex 69b86f0..bbcdfb2 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/home/Cards.kt@@ -251,8 +251,13 @@ fun NoteCard(note: Note, onOpen: () -> Unit, onLong: () -> Unit, modifier: Modif@Composablefun ThoughtCard(onOpen: () -> Unit, modifier: Modifier = Modifier) {val tone = clear.tone(Tone.Paper)+ // the day's quote on the card itself, so it reads as a thought before it is opened+ val res = androidx.compose.ui.platform.LocalContext.current.resources+ val quote = remember(res) { com.chethan616.clearpdf.notes.thoughtFor(res).quote }Column(modifier.heightIn(min = 188.dp).pressable(onOpen, pressedScale = 0.96f).cardPaint(tone, Offset(0.1f, 0.0f)).padding(18.dp)) {WordFitText(stringResource(R.string.thought_title), ClearType.CardTitle.copy(color = tone.accent), maxLines = 4)+ Spacer(Modifier.height(10.dp))+ Text("“$quote”", style = ClearType.Body.copy(fontSize = 14.sp, lineHeight = 19.sp, fontStyle = androidx.compose.ui.text.font.FontStyle.Italic), color = tone.ink.copy(alpha = 0.8f), maxLines = 5, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)Spacer(Modifier.weight(1f))Spacer(Modifier.height(12.dp))Text(shortDate(System.currentTimeMillis()), style = ClearType.Caption.copy(fontSize = 10.5.sp), color = tone.ink.copy(alpha = 0.55f), modifier = Modifier.align(Alignment.End))diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PresentMode.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PresentMode.ktnew file mode 100644index 0000000..747c9e9--- /dev/null+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/PresentMode.kt@@ -0,0 +1,110 @@+package com.chethan616.clearpdf.ui.viewer++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.pager.HorizontalPager+import androidx.compose.foundation.pager.rememberPagerState+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+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.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.core.view.WindowCompat+import androidx.core.view.WindowInsetsCompat+import androidx.core.view.WindowInsetsControllerCompat+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.engine.toBitmap+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.LocalBackdrop+import com.chethan616.clearpdf.ui.theme.ClearType+import com.kyant.backdrop.backdrops.layerBackdrop+import com.kyant.backdrop.backdrops.rememberLayerBackdrop+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * A presentation shown slide by slide, full screen on black: swipe, or tap the right or left of the+ * screen, to go on or back; the system bars hide while it shows. Each slide is drawn by DeckCraft at+ * the screen's size.+ */+@Composable+fun PresentMode(vm: AppViewModel, doc: OpenDocument, onClose: () -> Unit) {+ val eng = vm.engine ?: return+ val count = doc.pageCount+ val pager = rememberPagerState(initialPage = doc.viewer.currentPage.coerceIn(0, (count - 1).coerceAtLeast(0))) { count }+ val scope = rememberCoroutineScope()+ BackHandler(onBack = onClose)+ // full screen: the status and navigation bars hide while the show runs+ val view = LocalView.current+ DisposableEffect(view) {+ val window = (view.context as? android.app.Activity)?.window+ val controller = window?.let { WindowCompat.getInsetsController(it, view) }+ controller?.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE+ controller?.hide(WindowInsetsCompat.Type.systemBars())+ onDispose { controller?.show(WindowInsetsCompat.Type.systemBars()) }+ }+ val backdrop = rememberLayerBackdrop()+ Box(Modifier.fillMaxSize().background(Color.Black)) {+ BoxWithConstraints(Modifier.fillMaxSize().layerBackdrop(backdrop)) {+ val maxPx = constraints.maxWidth.toFloat()+ val maxPy = constraints.maxHeight.toFloat()+ HorizontalPager(pager, Modifier.fillMaxSize(), beyondViewportPageCount = 1) { i ->+ var slide by remember(i) { mutableStateOf<ImageBitmap?>(null) }+ LaunchedEffect(i, maxPx, maxPy) {+ val p = doc.info.pages.getOrNull(i) ?: return@LaunchedEffect+ // the scale that fits the slide to the screen+ val scale = minOf(maxPx / p.width, maxPy / p.height)+ slide = withContext(Dispatchers.Default) { runCatching { eng.command { renderPage(doc.id, i.toUInt(), scale, null) }.toBitmap().asImageBitmap() }.getOrNull() }+ }+ Box(+ Modifier.fillMaxSize().pointerInput(i) {+ detectTapGestures { at ->+ val next = if (at.x > size.width * 0.35f) i + 1 else i - 1+ if (next in 0 until count) scope.launch { pager.animateScrollToPage(next) } else if (next >= count) onClose()+ }+ },+ contentAlignment = Alignment.Center,+ ) { slide?.let { Image(it, null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit) } }+ }+ }+ CompositionLocalProvider(LocalBackdrop provides backdrop) {+ GlassCircle(onClick = onClose, modifier = Modifier.align(Alignment.TopStart).statusBarsPadding().padding(14.dp), label = stringResource(R.string.viewer_close), ink = Color.White) {+ GlassIcon(LucideIcons.X, null, Modifier.size(20.dp))+ }+ Text(+ stringResource(R.string.office_slide_of, pager.currentPage + 1, count),+ style = ClearType.Caption.copy(fontSize = 13.sp), color = Color.White.copy(alpha = 0.7f),+ modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 18.dp),+ )+ }+ }+}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 0f33d45..516b98f 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@@ -87,14 +87,30 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val tCreate("create", R.string.common_tool_create_pdf, R.string.common_tool_create_pdf, LucideIcons.FilePlus2, ToolHues.create),Text("text", R.string.toolbar_label_add_text, R.string.toolbar_tool_text, LucideIcons.Type, ToolHues.text),Scan("scan", R.string.common_tool_scan, R.string.common_tool_scan, LucideIcons.Camera, ToolHues.scan),- ReadAloud("readaloud", R.string.common_tool_read_aloud, R.string.common_tool_read_aloud, LucideIcons.Volume2, ToolHues.read);+ ReadAloud("readaloud", R.string.common_tool_read_aloud, R.string.common_tool_read_aloud, LucideIcons.Volume2, ToolHues.read),++ // 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),+ Print("print", R.string.sheet_print, R.string.sheet_print, LucideIcons.Printer, ToolHues.export);companion object {/** The bar as it comes: the reference's default tools and order. */val DEFAULT_BAR = listOf(Edit, Comment, Highlight, Draw, FillSign, Export)- /** The tools that work on a Word document or a presentation (they open for reading: the PDF tools don't apply). */- val WORD = listOf(ReadAloud)+ /** A Word document's bar: its engine reads it aloud, exports and converts it, and prints it. */+ val WORD = listOf(ReadAloud, ExportPdf, SaveAs, Print)++ /** A presentation's bar: a full-screen show first. */+ val SLIDES = listOf(Present, ReadAloud, ExportPdf, SaveAs, Print)++ /** The bar for [doc]: an office document's own tools, else the PDF bar as arranged. */+ fun barFor(doc: com.chethan616.clearpdf.ui.OpenDocument, arranged: List<QuickTool>): List<QuickTool> = when {+ doc.isSlides -> SLIDES+ doc.isOffice -> WORD+ else -> arranged+ }fun of(id: String): QuickTool? = entries.firstOrNull { it.id == id }}@@ -139,7 +155,7 @@ class QuickToolbarPrefs(context: Context) {/** Do what [tool] does on the bar or in More tools. */fun AppViewModel.runQuickTool(doc: OpenDocument, tool: QuickTool) {- if (doc.isOffice && tool !in QuickTool.WORD) {+ if (doc.isOffice && tool !in QuickTool.barFor(doc, emptyList())) {tell(com.chethan616.clearpdf.text(com.chethan616.clearpdf.R.string.msg_word_reading_only))return}@@ -163,6 +179,10 @@ fun AppViewModel.runQuickTool(doc: OpenDocument, tool: QuickTool) {QuickTool.Create -> openCreate()QuickTool.Scan -> startScan()QuickTool.ReadAloud -> startReadAloud(doc)+ QuickTool.Present -> presenting = doc+ QuickTool.ExportPdf -> exportOffice(doc, "pdf")+ QuickTool.SaveAs -> doc.controller.sheet = ViewerSheet.SaveAs+ QuickTool.Print -> print(doc)}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.ktindex 58ac478..1bc3c3d 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerBars.kt@@ -319,7 +319,7 @@ private fun dockSlots(widthDp: Int): Int = when {fun QuickToolbar(tools: List<QuickTool>,onTool: (QuickTool) -> Unit,- onMoreTools: () -> Unit,+ onMoreTools: (() -> Unit)?,moreToolsOpen: Boolean,) {val slots = dockSlots(LocalConfiguration.current.screenWidthDp)@@ -338,7 +338,8 @@ fun QuickToolbar(for (t in shown) DockItem(t.icon, stringResource(t.label)) { onTool(t) }}}- GlassCircle(onClick = onMoreTools, size = 60.dp, label = stringResource(R.string.common_tool_more_tools)) {+ // office documents have their own tools on the bar and no PDF More tools+ if (onMoreTools != null) GlassCircle(onClick = onMoreTools, size = 60.dp, label = stringResource(R.string.common_tool_more_tools)) {GlassIcon(LucideIcons.LayoutGrid, null, Modifier.size(23.dp).androidxRotate(turn))}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.ktindex 32f4e84..29949c7 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerController.kt@@ -36,7 +36,7 @@ enum class TextMarkup { Highlight, Underline, Strikethrough }enum class CommentMode { Text, Voice }/** What the bottom sheet over the viewer shows. */-enum class ViewerSheet { None, More, ViewSettings, Attachments, Bookmarks, Comments, MoreTools, Signatures }+enum class ViewerSheet { None, More, ViewSettings, Attachments, Bookmarks, Comments, MoreTools, Signatures, SaveAs }/*** The viewer's own state for one document, beside the page view ([ViewerState]): whether thediff --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 3478bfc..31d799a 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@@ -433,9 +433,9 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {Column(barSides) {if (ctl.tool == ViewerTool.None) {QuickToolbar(- tools = if (doc.isOffice) QuickTool.WORD else vm.quickToolbar.bar,+ tools = QuickTool.barFor(doc, vm.quickToolbar.bar),onTool = { vm.runQuickTool(doc, it) },- onMoreTools = { ctl.sheet = if (ctl.sheet == ViewerSheet.MoreTools) ViewerSheet.None else ViewerSheet.MoreTools },+ onMoreTools = if (doc.isOffice) null else ({ ctl.sheet = if (ctl.sheet == ViewerSheet.MoreTools) ViewerSheet.None else ViewerSheet.MoreTools }),moreToolsOpen = ctl.sheet == ViewerSheet.MoreTools,)} else {@@ -467,6 +467,7 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {ViewerSheet.Attachments -> AttachmentsSheet(vm, doc)ViewerSheet.Comments -> UnitViewerSheet.MoreTools -> MoreToolsSheet(vm, doc)+ ViewerSheet.SaveAs -> SaveAsSheet(vm, doc)ViewerSheet.Signatures -> SignaturesSheet(vm, doc)ViewerSheet.None -> Unit}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 6dd6d84..f991690 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@@ -132,11 +132,9 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {stringResource(if (bookmarked) R.string.sheet_remove_bookmark else R.string.sheet_add_bookmark), Candy.Tangerine,) { close(); vm.toggleBookmark(doc) }ActionTile(LucideIcons.Volume2, stringResource(R.string.common_tool_read_aloud), Candy.Sky) { close(); vm.startReadAloud(doc) }- // a Word document opens for reading: editing and printing it come later- if (!doc.isOffice) {- ActionTile(LucideIcons.FilePenLine, stringResource(R.string.common_tool_edit_pdf), Candy.Bubblegum) { close(); vm.enterTool(doc, ViewerTool.Edit) }- ActionTile(LucideIcons.Printer, stringResource(R.string.sheet_print), Candy.Grape) { close(); vm.print(doc) }- }+ if (doc.isSlides) ActionTile(LucideIcons.Presentation, stringResource(R.string.office_present), Candy.Bubblegum) { close(); vm.presenting = doc }+ else if (!doc.isOffice) ActionTile(LucideIcons.FilePenLine, stringResource(R.string.common_tool_edit_pdf), Candy.Bubblegum) { close(); vm.enterTool(doc, ViewerTool.Edit) }+ ActionTile(LucideIcons.Printer, stringResource(R.string.sheet_print), Candy.Grape) { close(); vm.print(doc) }}Spacer(Modifier.height(8.dp))SheetSection {@@ -149,6 +147,11 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {SheetRow(LucideIcons.ShieldCheck, stringResource(R.string.sign_signatures), { ctl.sheet = ViewerSheet.Signatures }, chevron = true, tint = Candy.Lime)}}+ // an office document: written by its own engine as PDF or another format+ if (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)+ }if (!doc.isOffice) SheetSection {SheetRow(LucideIcons.FileOutput, stringResource(R.string.sheet_export_as), { close(); vm.openExport(doc) }, tint = Candy.Tangerine)SheetRow(LucideIcons.FileArchive, stringResource(R.string.common_tool_compress), { close(); vm.openCompress(doc) }, tint = Candy.Mint)@@ -577,3 +580,40 @@ fun MoreToolsSheet(vm: AppViewModel, doc: OpenDocument) {Spacer(Modifier.height(12.dp))}}+++/** Save as: the formats the document's engine writes, each saved to Downloads. */+@Composable+fun SaveAsSheet(vm: AppViewModel, doc: OpenDocument) {+ val ctl = doc.controller+ var formats by remember { mutableStateOf<List<String>>(emptyList()) }+ LaunchedEffect(doc.id) { formats = vm.engine?.let { e -> runCatching { e.command { exportFormats(doc.id) } }.getOrNull() }.orEmpty() }+ 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()), {+ ctl.sheet = ViewerSheet.None+ vm.exportOffice(doc, f)+ }, tint = Candy.Sky)+ }+ Spacer(Modifier.height(10.dp))+ }+}++/** A format's name as people know it. */+@Composable+private fun formatName(f: String): String = stringResource(+ when (f) {+ "pdf" -> R.string.format_pdf+ "docx" -> R.string.format_docx+ "odt" -> R.string.format_odt+ "rtf" -> R.string.format_rtf+ "html" -> R.string.format_html+ "md" -> R.string.format_md+ "txt" -> R.string.format_txt+ "pptx" -> R.string.format_pptx+ "xlsx" -> R.string.format_xlsx+ "csv" -> R.string.format_csv+ else -> R.string.format_other+ },+)diff --git a/android/app/src/main/res/anim/preview_open_enter.xml b/android/app/src/main/res/anim/preview_open_enter.xmlindex 0e16b63..03c597e 100644--- a/android/app/src/main/res/anim/preview_open_enter.xml+++ b/android/app/src/main/res/anim/preview_open_enter.xml@@ -1,13 +1,10 @@<?xml version="1.0" encoding="utf-8"?>-<!-- The full viewer, coming in over Quick Preview's card: it rises from where the card is while it fades in -->+<!-- The app, coming in over Quick Preview's card: a short fade onto the viewer's plain ground; the+ document then rises over it as it does when opened from the desk --><set xmlns:android="http://schemas.android.com/apk/res/android"android:interpolator="@interpolator/ui_curve">- <translate- android:fromYDelta="9%p"- android:toYDelta="0"- android:duration="420" /><alphaandroid:fromAlpha="0"android:toAlpha="1"- android:duration="300" />+ android:duration="180" /></set>diff --git a/android/app/src/main/res/anim/preview_open_exit.xml b/android/app/src/main/res/anim/preview_open_exit.xmlindex 829193d..533f88c 100644--- a/android/app/src/main/res/anim/preview_open_exit.xml+++ b/android/app/src/main/res/anim/preview_open_exit.xml@@ -1,8 +1,8 @@<?xml version="1.0" encoding="utf-8"?>-<!-- Quick Preview's card stays exactly where it is until the viewer has covered it -->+<!-- Quick Preview's card stays exactly where it is until the app has faded in over it --><set xmlns:android="http://schemas.android.com/apk/res/android"><alphaandroid:fromAlpha="1"android:toAlpha="1"- android:duration="420" />+ android:duration="180" /></set>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 1ed197a..6381570 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -958,6 +958,28 @@<string name="msg_word_reading_only">Word documents and presentations open for reading for now. Editing them is coming.</string><string name="sheet_kind_word">Word</string><string name="sheet_kind_slides">Slides</string>+ <string name="office_present">Present</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>+ <string name="office_slide_of">%1$d of %2$d</string>+ <string name="format_pdf">PDF</string>+ <string name="format_docx">Word document</string>+ <string name="format_odt">OpenDocument text</string>+ <string name="format_rtf">Rich text</string>+ <string name="format_html">Web page</string>+ <string name="format_md">Markdown</string>+ <string name="format_txt">Plain text</string>+ <string name="format_pptx">PowerPoint presentation</string>+ <string name="format_xlsx">Excel workbook</string>+ <string name="format_csv">Comma-separated values</string>+ <string name="format_other">Other</string>+ <string name="files_kind_all">All files</string>+ <string name="files_kind_pdf">PDFs</string>+ <string name="files_kind_word">Word documents</string>+ <string name="files_kind_slides">Presentations</string>+ <string name="files_kind_sheets">Spreadsheets</string>+ <string name="files_kind_text">Text files</string><string name="photo_exposure">Exposure</string><string name="photo_contrast">Contrast</string><string name="photo_highlights">Highlights</string>diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 1e7454f..468928b 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -129,6 +129,7 @@ version = "0.14.0"dependencies = ["android_logger","deckcraft-model",+ "deckcraft-pdf","deckcraft-pptx","deckcraft-render","gridcraft-engine",@@ -990,6 +991,15 @@ version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"+[[package]]+name = "core_maths"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"+dependencies = [+ "libm",+]+[[package]]name = "cow-utils"version = "0.1.3"@@ -1287,6 +1297,23 @@ dependencies = ["unicode-segmentation",]+[[package]]+name = "deckcraft-pdf"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "craft-pdf",+ "deckcraft-fonts",+ "deckcraft-model",+ "deckcraft-render",+ "deckcraft-text",+ "krilla",+ "kurbo",+ "log",+ "serde",+ "thiserror 2.0.21",+]+[[package]]name = "deckcraft-pptx"version = "0.15.0"@@ -2974,7 +3001,9 @@ dependencies = ["indexmap","pdf-writer","png",+ "rayon","rustc-hash",+ "rustybuzz","siphasher","skrifa 0.42.1","smallvec",@@ -3004,6 +3033,12 @@ version = "0.2.189"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+[[package]]name = "lightcraft-codecs"version = "0.18.0"@@ -5066,6 +5101,24 @@ dependencies = ["wait-timeout",]+[[package]]+name = "rustybuzz"+version = "0.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "core_maths",+ "log",+ "smallvec",+ "ttf-parser",+ "unicode-bidi-mirroring",+ "unicode-ccc",+ "unicode-properties",+ "unicode-script",+]+[[package]]name = "ryu"version = "1.0.23"@@ -5816,7 +5869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.4.3",+ "getrandom 0.3.4","once_cell","rustix","windows-sys 0.61.2",@@ -6153,6 +6206,15 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+dependencies = [+ "core_maths",+]+[[package]]name = "typeid"version = "1.0.3"@@ -6188,6 +6250,18 @@ version = "0.3.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"+[[package]]+name = "unicode-bidi-mirroring"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"++[[package]]+name = "unicode-ccc"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"+[[package]]name = "unicode-ident"version = "1.0.26"diff --git a/engine/Cargo.toml b/engine/Cargo.tomlindex 2fdbc2f..d2e47a7 100644--- a/engine/Cargo.toml+++ b/engine/Cargo.toml@@ -65,6 +65,8 @@ wordcraft-engine = { path = "vendor/wordcraft-engine", version = "0.15.1", defaudeckcraft-model = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }deckcraft-pptx = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }deckcraft-render = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }+# slides to PDF (craft-pdf through the krilla fork patched in below)+deckcraft-pdf = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }# Excel (.xlsx, .xlsb, .ods, .csv): storytold/gridcraft's engine (formulas, number formats), pinned.gridcraft-engine = { git = "https://github.com/storytold/gridcraft", rev = "6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214", version = "0.16.0" }diff --git a/engine/mobile/Cargo.toml b/engine/mobile/Cargo.tomlindex e6d11e6..7f7598b 100644--- a/engine/mobile/Cargo.toml+++ b/engine/mobile/Cargo.toml@@ -26,6 +26,7 @@ wordcraft-engine = { workspace = true }deckcraft-model = { workspace = true }deckcraft-pptx = { workspace = true }deckcraft-render = { workspace = true }+deckcraft-pdf = { workspace = true }# Excel workbooks (src/sheets.rs): GridCraft's enginegridcraft-engine = { workspace = true }gridcraft-xlsx = { workspace = true }diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rsindex 391f709..7347bdc 100644--- a/engine/mobile/src/lib.rs+++ b/engine/mobile/src/lib.rs@@ -878,6 +878,19 @@ impl MobileSession {})}+ /// Write office document `doc` (Word, slides or a workbook) as `format` to absolute path `path`:+ /// `pdf`, or another format its engine writes ([`MobileSession::export_formats`]).+ pub fn export_office(&self, doc: u64, format: String, path: String) -> Result<(), MobileError> {+ let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;+ let bytes = d.export(&format.to_ascii_lowercase())?;+ std::fs::write(&path, bytes).map_err(|e| MobileError::Command(format!("{path}: {e}")))+ }++ /// The formats office document `doc` can be written as, PDF first (empty for a PDF).+ pub fn export_formats(&self, doc: u64) -> Vec<String> {+ self.office(doc).map(|d| office::formats(d.info(doc).kind).iter().map(|f| f.to_string()).collect()).unwrap_or_default()+ }+/// 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 feee168..acae4dc 100644--- a/engine/mobile/src/office.rs+++ b/engine/mobile/src/office.rs@@ -34,6 +34,9 @@ pub(crate) trait OfficeDoc: Send + Sync {/// Drop what can be built again (the system is short of memory).fn release_memory(&self);+ /// The document written as `format` (`pdf`, or one its engine writes: see [`formats`]).+ fn export(&self, format: &str) -> Result<Vec<u8>, MobileError>;+/// A workbook, whose sheets the app draws as a grid of its own.fn as_sheets(&self) -> Option<&crate::sheets::SheetBook> {None@@ -120,13 +123,18 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {if head.starts_with(b"{\\rtf") {return Some(OfficeFile::Word("rtf"));}- // plain-text tables are known by their name alone- if let Some(e @ ("csv" | "tsv")) = sheets_named- && !head.contains(&0)- {+ // plain text is known by its name alone: tables, and prose the Word engine reads+ if head.contains(&0) {+ return None;+ }+ if let Some(e @ ("csv" | "tsv")) = sheets_named {return Some(OfficeFile::Sheets(e));}- None+ match ext.as_deref() {+ Some("txt") => Some(OfficeFile::Word("txt")),+ Some("md" | "markdown") => Some(OfficeFile::Word("md")),+ _ => None,+ }}/// Read the file at `path` within the size bound.@@ -146,8 +154,8 @@ pub(crate) fn file_at(path: &str) -> Result<Option<(OfficeFile, Vec<u8>)>, Mobillet n = std::fs::File::open(path).and_then(|mut f| f.read(&mut head)).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;let head = head.get(..n).unwrap_or_default();let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default();- let text_table = ext.eq_ignore_ascii_case("csv") || ext.eq_ignore_ascii_case("tsv");- if !(text_table || head.starts_with(b"PK\x03\x04") || head.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) || head.starts_with(b"{\\rtf")) {+ let plain = ["csv", "tsv", "txt", "md", "markdown"].iter().any(|e| ext.eq_ignore_ascii_case(e));+ if !(plain || head.starts_with(b"PK\x03\x04") || head.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) || head.starts_with(b"{\\rtf")) {return Ok(None);}let bytes = read(path)?;@@ -169,6 +177,21 @@ pub(crate) fn open(})}+/// The formats an office document of `kind` can be written as, PDF first.+pub(crate) fn formats(kind: crate::DocumentKind) -> &'static [&'static str] {+ match kind {+ crate::DocumentKind::Word => &["pdf", "docx", "odt", "rtf", "html", "md", "txt"],+ crate::DocumentKind::Slides => &["pdf", "pptx"],+ crate::DocumentKind::Sheets => &["pdf", "xlsx", "csv"],+ crate::DocumentKind::Pdf => &[],+ }+}++/// A refusal of `format` for a document of `kind`.+pub(crate) fn unknown_format(kind: crate::DocumentKind, format: &str) -> MobileError {+ MobileError::Command(format!("a {kind:?} document can't be written as {format}: it can be {}", formats(kind).join(", ")))+}+/// The file name of `path`.pub(crate) fn file_name(path: &str) -> String {std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string())@@ -221,6 +244,8 @@ mod tests {assert_eq!(sniff(b"a,b\n1,2\n", "/a/t.csv"), Some(OfficeFile::Sheets("csv")));assert_eq!(sniff(b"{\\rtf1\\ansi hello}", "/a/x.txt"), Some(OfficeFile::Word("rtf")));assert_eq!(sniff(b"plain words", "/a/notes.docx"), None);+ assert_eq!(sniff(b"plain words", "/a/notes.txt"), Some(OfficeFile::Word("txt")));+ assert_eq!(sniff(b"# Title", "/a/Read me.md"), Some(OfficeFile::Word("md")));}#[test]diff --git a/engine/mobile/src/sheets.rs b/engine/mobile/src/sheets.rsindex 34dcf53..f40b662 100644--- a/engine/mobile/src/sheets.rs+++ b/engine/mobile/src/sheets.rs@@ -389,6 +389,25 @@ impl OfficeDoc for SheetBook {fn release_memory(&self) {}+ fn export(&self, format: &str) -> Result<Vec<u8>, MobileError> {+ 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 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()))+ }+ _ => Err(crate::office::unknown_format(DocumentKind::Sheets, format)),+ }+ }+fn as_sheets(&self) -> Option<&SheetBook> {Some(self)}diff --git a/engine/mobile/src/slides.rs b/engine/mobile/src/slides.rsindex 3da9f68..8dcb0bf 100644--- a/engine/mobile/src/slides.rs+++ b/engine/mobile/src/slides.rs@@ -149,6 +149,14 @@ impl OfficeDoc for SlideDeck {.collect())}+ fn export(&self, format: &str) -> Result<Vec<u8>, MobileError> {+ match format {+ "pdf" => deckcraft_pdf::export(&self.pres, &deckcraft_pdf::PdfOptions::default()).map_err(|e| MobileError::Command(e.to_string())),+ "pptx" => deckcraft_pptx::export(&self.pres).map_err(|e| MobileError::Command(e.to_string())),+ _ => Err(crate::office::unknown_format(DocumentKind::Slides, format)),+ }+ }+fn release_memory(&self) {let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner);texts.iter_mut().for_each(|t| *t = None);diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rsindex b37c04f..7710742 100644--- a/engine/mobile/src/tests.rs+++ b/engine/mobile/src/tests.rs@@ -627,3 +627,30 @@ fn develops_a_photo_and_saves_it() {e.export_jpeg(path, r#"{"light":{"exposure":0.5}}"#.into(), out.clone(), 90).unwrap();assert!(std::fs::read(out).unwrap().starts_with(&[0xFF, 0xD8]));}++#[test]+fn office_documents_export_to_pdf_and_their_own_formats() {+ let s = MobileSession::new();+ let dir = scratch();+ let cases = [+ (word_file("Exported words.", "W.docx"), vec!["pdf", "docx", "odt", "rtf", "html", "md", "txt"]),+ (deck_file("Exported slide", "S.pptx"), vec!["pdf", "pptx"]),+ (book_file("a,b\n1,2\n", "B.xlsx"), vec!["pdf", "xlsx", "csv"]),+ ];+ for (path, formats) in cases {+ let id = s.open(path.clone(), None).unwrap().id;+ assert_eq!(s.export_formats(id), formats, "{path}");+ for f in &formats {+ let out = dir.join(format!("out.{f}")).to_string_lossy().into_owned();+ s.export_office(id, f.to_string(), out.clone()).unwrap_or_else(|e| panic!("{path} as {f}: {e}"));+ let bytes = std::fs::read(&out).unwrap();+ assert!(!bytes.is_empty(), "{path} as {f}");+ if *f == "pdf" {+ assert!(bytes.starts_with(b"%PDF"), "{path} as pdf");+ // and it opens in the PDF engine+ assert!(!s.open(out.clone(), None).unwrap().pages.is_empty());+ }+ }+ assert!(s.export_office(id, "exe".into(), dir.join("x").to_string_lossy().into_owned()).is_err());+ }+}diff --git a/engine/mobile/src/word.rs b/engine/mobile/src/word.rsindex 3bb09ff..a2049a2 100644--- a/engine/mobile/src/word.rs+++ b/engine/mobile/src/word.rs@@ -170,6 +170,15 @@ impl OfficeDoc for WordDocument {Ok(out)}+ fn export(&self, format: &str) -> Result<Vec<u8>, MobileError> {+ if !crate::office::formats(DocumentKind::Word).contains(&format) {+ return Err(crate::office::unknown_format(DocumentKind::Word, format));+ }+ let s = self.lock();+ // the engine picks its writer by the name's extension+ wordcraft_engine::io::save_bytes(&format!("document.{format}"), &s.session.doc).map_err(MobileError::Command)+ }+/// 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());diff --git a/samples/AppBody-Sample-English.docx b/samples/AppBody-Sample-English.docxnew file mode 100644index 0000000..4b8185cBinary files /dev/null and b/samples/AppBody-Sample-English.docx differdiff --git a/samples/file-example_PDF_1MB.pdf b/samples/file-example_PDF_1MB.pdfnew file mode 100644index 0000000..13ce574Binary files /dev/null and b/samples/file-example_PDF_1MB.pdf differdiff --git a/samples/file_example_PPT_1MB.ppt b/samples/file_example_PPT_1MB.pptnew file mode 100644index 0000000..769693dBinary files /dev/null and b/samples/file_example_PPT_1MB.ppt differdiff --git a/samples/file_example_XLSX_100.xlsx b/samples/file_example_XLSX_100.xlsxnew file mode 100644index 0000000..11855fcBinary files /dev/null and b/samples/file_example_XLSX_100.xlsx differ