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
feat: list folders picked through SAF instead of all-files access, plus tool bar and bottom bar updates
Josh531e025e22d5
diff --git a/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xml b/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xmlindex 539f622..557f87f 100644--- a/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xml+++ b/apps/pdfcraft-android/android/app/src/main/AndroidManifest.xml@@ -1,10 +1,8 @@<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android">- <!-- Files ▸ On this device: PDFs anywhere in shared storage (Android 11+ asks in Settings; earlier, a prompt) -->- <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" />+ <!-- No storage permission: files come through the system's pickers (On this device lists the+ folders the user picks), and what the app saves goes to Downloads through the media store --><!-- Comment ▸ Voice: recording a voice comment (asked for when first used) --><uses-permission android:name="android.permission.RECORD_AUDIO" />diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.ktindex be521be..0514687 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/MainActivity.kt@@ -48,7 +48,7 @@ class MainActivity : ComponentActivity() {private val pickImage = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> vm.addImage(uri) }private val pickSignature = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> vm.importSignatureImage(uri) }private val pickPhotos = registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { uris -> vm.onPhotosPicked(uris) }- private val storagePermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { vm.onResumed() }+ private val pickFolder = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> uri?.let(vm::addLocalFolder) }private val micPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> vm.onMicPermission(granted) }override fun onCreate(savedInstanceState: Bundle?) {@@ -98,7 +98,9 @@ class MainActivity : ComponentActivity() {}lifecycleScope.launch { for (d in vm.imagePicks) launchSafely { pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } }lifecycleScope.launch { for (u in vm.photoPicks) launchSafely { pickPhotos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } }- lifecycleScope.launch { for (u in vm.accessRequests) askForFileAccess() }+ // the folder picker opens at Documents, where PDFs usually are (Download itself can't be chosen)+ val documents = android.provider.DocumentsContract.buildDocumentUri("com.android.externalstorage.documents", "primary:Documents")+ lifecycleScope.launch { for (u in vm.accessRequests) launchSafely { pickFolder.launch(documents) } }lifecycleScope.launch {for (u in vm.micRequests) {// refused before: explain first (the reference's order); otherwise Android's own prompt@@ -137,17 +139,6 @@ class MainActivity : ComponentActivity() {}}- /** All-files access (Android 11+), or the storage permission before it. */- private fun askForFileAccess() {- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {- launchSafely {- startActivity(Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName")))- }- } else {- storagePermission.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE)- }- }-override fun onPause() {super.onPause()vm.onPause()diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/LocalFiles.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/LocalFiles.ktindex 71f0d25..d05da44 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/LocalFiles.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/engine/LocalFiles.kt@@ -1,13 +1,14 @@package io.github.artcraftandroid.pdfcraft.engine-import android.content.ContentUrisimport android.content.Context+import android.content.Intentimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.net.Uri-import android.os.Build-import android.os.Environment+import android.content.ContentUris+import android.provider.DocumentsContractimport android.provider.MediaStore+import android.provider.OpenableColumnsimport io.github.artcraftandroid.pdfcraft.core.fileThumbnailimport java.io.Fileimport java.security.MessageDigest@@ -16,16 +17,99 @@ import java.security.MessageDigestdata class LocalPdf(val uri: Uri, val path: String?, val name: String, val folder: String, val size: Long, val modified: Long)/**- * The PDFs on the phone's storage, found through the media store (every PDF with all-files- * access, only the app's own without it), newest first.+ * The PDFs in the folders the user has chosen for "On this device", and the ones PdfCraft saved+ * itself (copies, scans, combined files in Downloads, which the media store shows an app without+ * any permission), newest first. Folders are picked with the system's folder picker (no access to+ * all files): the app keeps a lasting grant for each one and reads, saves, renames and deletes its+ * files through the document provider.*/object LocalFiles {- /** Whether the app may see every file (Android 11+: all-files access; earlier: storage permission). */- fun hasAccess(context: Context): Boolean =- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Environment.isExternalStorageManager()- else context.checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == android.content.pm.PackageManager.PERMISSION_GRANTED+ /** At most this many entries are looked at in all, and folders this deep, so a huge tree can't stall the list. */+ private const val MAX_ENTRIES = 20_000+ private const val MAX_DEPTH = 8++ /** The folders the user has added (the lasting grants that are folders). */+ fun folders(context: Context): List<Uri> =+ runCatching { context.contentResolver.persistedUriPermissions }.getOrDefault(emptyList())+ .filter { it.isReadPermission && runCatching { DocumentsContract.isTreeUri(it.uri) }.getOrDefault(false) }+ .map { it.uri }++ /** Whether any folder has been added. */+ fun hasAccess(context: Context): Boolean = folders(context).isNotEmpty()++ /** Keep [tree] (from the folder picker) for good: with writing when the provider allows it. */+ fun addFolder(context: Context, tree: Uri) {+ val resolver = context.contentResolver+ runCatching { resolver.takePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) }+ .recoverCatching { resolver.takePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION) }+ }++ /** Stop listing [tree] and give its grant back. */+ fun removeFolder(context: Context, tree: Uri) {+ val resolver = context.contentResolver+ runCatching { resolver.releasePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) }+ .recoverCatching { resolver.releasePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION) }+ }++ /** A folder's name as its provider gives it ("Download", "Documents"). */+ fun folderName(context: Context, tree: Uri): String = runCatching {+ val doc = DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))+ context.contentResolver.query(doc, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst()) c.getString(0) else null+ }+ }.getOrNull() ?: tree.lastPathSegment?.substringAfterLast(':')?.ifEmpty { null } ?: "Folder"fun scan(context: Context): List<LocalPdf> {+ val resolver = context.contentResolver+ val out = ArrayList<LocalPdf>()+ val seen = HashSet<String>()+ var looked = 0+ val cols = arrayOf(+ DocumentsContract.Document.COLUMN_DOCUMENT_ID,+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,+ DocumentsContract.Document.COLUMN_MIME_TYPE,+ DocumentsContract.Document.COLUMN_SIZE,+ DocumentsContract.Document.COLUMN_LAST_MODIFIED,+ )+ for (tree in folders(context)) {+ val rootId = runCatching { DocumentsContract.getTreeDocumentId(tree) }.getOrNull() ?: continue+ // breadth first: (folder id, its name, depth)+ val queue = ArrayDeque<Triple<String, String, Int>>()+ queue.add(Triple(rootId, folderName(context, tree), 0))+ while (queue.isNotEmpty() && looked < MAX_ENTRIES) {+ val (dirId, dirName, depth) = queue.removeFirst()+ val children = runCatching { DocumentsContract.buildChildDocumentsUriUsingTree(tree, dirId) }.getOrNull() ?: continue+ runCatching {+ resolver.query(children, cols, null, null, null)?.use { c ->+ while (c.moveToNext() && looked < MAX_ENTRIES) {+ looked+++ val id = c.getString(0) ?: continue+ val name = c.getString(1) ?: continue+ if (name.startsWith(".")) continue+ val mime = c.getString(2)+ if (mime == DocumentsContract.Document.MIME_TYPE_DIR) {+ if (depth + 1 <= MAX_DEPTH) queue.add(Triple(id, name, depth + 1))+ continue+ }+ if (mime != "application/pdf" && !name.endsWith(".pdf", ignoreCase = true)) continue+ // a folder added twice (or inside another) lists its files once+ if (!seen.add(id)) continue+ val uri = DocumentsContract.buildDocumentUriUsingTree(tree, id)+ val size = if (c.isNull(3)) 0L else c.getLong(3)+ val modified = if (c.isNull(4)) 0L else c.getLong(4)+ out.add(LocalPdf(uri, null, name, dirName, size, modified))+ }+ }+ }+ }+ }+ out.addAll(ownFiles(context))+ out.sortByDescending { it.modified }+ return out+ }++ /** The PDFs this app put in shared storage itself (the media store lists only those to it). */+ private fun ownFiles(context: Context): List<LocalPdf> {val out = ArrayList<LocalPdf>()val collection = MediaStore.Files.getContentUri("external")val projection = arrayOf(@@ -34,26 +118,15 @@ object LocalFiles {MediaStore.Files.FileColumns.SIZE,MediaStore.Files.FileColumns.DATE_MODIFIED,MediaStore.Files.FileColumns.RELATIVE_PATH,- @Suppress("DEPRECATION") MediaStore.Files.FileColumns.DATA,)val selection = "${MediaStore.Files.FileColumns.MIME_TYPE} = ? OR ${MediaStore.Files.FileColumns.DISPLAY_NAME} LIKE ?"runCatching {- context.contentResolver.query(collection, projection, selection, arrayOf("application/pdf", "%.pdf"), "${MediaStore.Files.FileColumns.DATE_MODIFIED} DESC")?.use { c ->- val idCol = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)- val nameCol = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)- val sizeCol = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)- val dateCol = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED)- val relCol = c.getColumnIndex(MediaStore.Files.FileColumns.RELATIVE_PATH)- @Suppress("DEPRECATION") val dataCol = c.getColumnIndex(MediaStore.Files.FileColumns.DATA)+ context.contentResolver.query(collection, projection, selection, arrayOf("application/pdf", "%.pdf"), null)?.use { c ->while (c.moveToNext()) {- val name = c.getString(nameCol) ?: continue+ val name = c.getString(1) ?: continueif (name.startsWith(".")) continue- val path = if (dataCol >= 0) c.getString(dataCol) else null- // a file the app reads by path when it may (so saving writes in place)- val uri = if (path != null && hasAccess(context)) Uri.fromFile(File(path)) else ContentUris.withAppendedId(collection, c.getLong(idCol))- val rel = if (relCol >= 0) c.getString(relCol) else null- val folder = rel?.trimEnd('/')?.substringAfterLast('/') ?: path?.let { File(it).parentFile?.name } ?: ""- out.add(LocalPdf(uri, path, name, folder, c.getLong(sizeCol), c.getLong(dateCol) * 1000))+ val folder = c.getString(4)?.trimEnd('/')?.substringAfterLast('/') ?: ""+ out.add(LocalPdf(ContentUris.withAppendedId(collection, c.getLong(0)), null, name, folder, c.getLong(2), c.getLong(3) * 1000))}}}@@ -63,32 +136,63 @@ object LocalFiles {/*** Small pictures of documents' first pages for file lists, rendered by the engine and kept on- * disk (keyed by the file and its last change), so a list scrolls without re-rendering.+ * disk (keyed by the file and its last change), so a list scrolls without re-rendering. A file is+ * given by its path, or by its content address (a document in a chosen folder), which is copied+ * to a scratch file just long enough to draw it.*/-class Thumbnails(context: Context) {+class Thumbnails(private val context: Context) {private val dir = File(context.cacheDir, "thumbs").apply { mkdirs() }private val memory = object : android.util.LruCache<String, Bitmap>(12 * 1024 * 1024) {override fun sizeOf(key: String, value: Bitmap) = value.byteCount}- /** The thumbnail of the PDF at [path] (null when it can't be drawn: protected, damaged). Blocking. */+ /** The thumbnail of the PDF at [path] or content address (null when it can't be drawn: protected, damaged). Blocking. */fun of(path: String, maxSide: Int = 160): Bitmap? {+ if (path.startsWith("content:")) return ofContent(Uri.parse(path), maxSide)val f = File(path)if (!f.isFile) return null- val key = sha("$path|${f.lastModified()}|${f.length()}|$maxSide")+ return cached(sha("$path|${f.lastModified()}|${f.length()}|$maxSide")) { fileThumbnail(path, maxSide.toUInt()).toBitmap() }+ }++ private fun ofContent(uri: Uri, maxSide: Int): Bitmap? {+ val resolver = context.contentResolver+ val (size, modified) = runCatching {+ resolver.query(uri, arrayOf(OpenableColumns.SIZE, DocumentsContract.Document.COLUMN_LAST_MODIFIED), null, null, null)?.use { c ->+ if (!c.moveToFirst()) null+ else (if (c.isNull(0)) 0L else c.getLong(0)) to (if (c.columnCount > 1 && !c.isNull(1)) c.getLong(1) else 0L)+ }+ }.getOrNull() ?: return null+ // a very large file isn't copied just for its first page+ if (size > MAX_COPY) return null+ return cached(sha("$uri|$modified|$size|$maxSide")) {+ val tmp = File.createTempFile("thumb", ".pdf", context.cacheDir)+ try {+ resolver.openInputStream(uri)?.use { input -> tmp.outputStream().use { input.copyTo(it) } } ?: error("unreadable")+ fileThumbnail(tmp.absolutePath, maxSide.toUInt()).toBitmap()+ } finally {+ tmp.delete()+ }+ }+ }++ private fun cached(key: String, draw: () -> Bitmap): Bitmap? {memory.get(key)?.let { return it }- val cached = File(dir, "$key.png")- if (cached.isFile) {- BitmapFactory.decodeFile(cached.absolutePath)?.let {+ val file = File(dir, "$key.png")+ if (file.isFile) {+ BitmapFactory.decodeFile(file.absolutePath)?.let {memory.put(key, it)return it}}- val bmp = runCatching { fileThumbnail(path, maxSide.toUInt()).toBitmap() }.getOrNull() ?: return null- runCatching { cached.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 90, it) } }+ val bmp = runCatching(draw).getOrNull() ?: return null+ runCatching { file.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 90, it) } }memory.put(key, bmp)return bmp}private fun sha(s: String) = MessageDigest.getInstance("SHA-1").digest(s.toByteArray()).joinToString("") { "%02x".format(it) }++ private companion object {+ const val MAX_COPY = 100L * 1024 * 1024+ }}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.ktindex 6b18110..0f1c7c6 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt@@ -103,6 +103,9 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {/** Open the PDF at [uri] (picked, shared, or from Recent), asking for its password if it has one. */fun open(uri: Uri, password: String? = null) {+ // a file opened from another app comes to the front, not under Settings+ settingsOpen = false+ showLicences = falseviewModelScope.launch {val eng = engine ?: application.engine.await().getOrNull() ?: run { tell(engineProblem ?: "PdfCraft couldn't start."); return@launch }opening = true@@ -253,6 +256,10 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}}save(doc)+ // Recent shows the size the file has now, not the size it had when opened+ withContext(Dispatchers.IO) {+ doc.source?.let { src -> files.size(src)?.let { size -> recents.update(src.toString()) { it.copy(size = size) } } }+ }closeQuietly(eng, doc)}@@ -472,6 +479,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {* Up for the previous one, the arrows to scroll, Ctrl+P to print, Ctrl and + or − to zoom.*/fun viewerKey(keyCode: Int, ctrl: Boolean): Boolean {+ if (!keyboardShortcuts) return falseval doc = document ?: return falseif (toolScreen != null || readingMode) return falseval v = doc.viewer@@ -730,6 +738,15 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {appPrefs.edit().putBoolean("keepScreenOn", on).apply()}+ /** The viewer's keyboard shortcuts (Preferences; off until turned on, as the reference has them). */+ var keyboardShortcuts by mutableStateOf(appPrefs.getBoolean("keyboardShortcuts", false))+ private set++ fun updateKeyboardShortcuts(on: Boolean) {+ keyboardShortcuts = on+ appPrefs.edit().putBoolean("keyboardShortcuts", on).apply()+ }+/** The app's theme (Preferences ▸ Theme): the system's, or always light or dark. */var theme by mutableStateOf(runCatching { ThemeChoice.valueOf(appPrefs.getString("theme", "System") ?: "System") }.getOrDefault(ThemeChoice.System))private set@@ -1890,13 +1907,33 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {}}- /** All-files access: the activity opens the system page for it. */+ /** Adding a folder to On this device: the activity opens the system's folder picker. */val accessRequests = Channel<Unit>(Channel.CONFLATED)fun requestFileAccess() {accessRequests.trySend(Unit)}+ /** The folders On this device lists, with their names. */+ fun localFolders(): List<Pair<Uri, String>> {+ val app = getApplication<Application>()+ return io.github.artcraftandroid.pdfcraft.engine.LocalFiles.folders(app).map { it to io.github.artcraftandroid.pdfcraft.engine.LocalFiles.folderName(app, it) }+ }++ /** A folder chosen in the picker: list its PDFs from now on. */+ fun addLocalFolder(tree: Uri) {+ io.github.artcraftandroid.pdfcraft.engine.LocalFiles.addFolder(getApplication(), tree)+ hasFileAccess = io.github.artcraftandroid.pdfcraft.engine.LocalFiles.hasAccess(getApplication())+ scanLocal(force = true)+ }++ /** Stop listing [tree]. */+ fun removeLocalFolder(tree: Uri) {+ io.github.artcraftandroid.pdfcraft.engine.LocalFiles.removeFolder(getApplication(), tree)+ hasFileAccess = io.github.artcraftandroid.pdfcraft.engine.LocalFiles.hasAccess(getApplication())+ scanLocal(force = true)+ }+/** Back from the access page (or the app resumed): look again. */fun onResumed() {val had = hasFileAccess@@ -1905,12 +1942,12 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {refreshRecents()}- /** A local path for [uri]'s thumbnail: the file itself, or the app's working copy of it. */+ /** What [uri]'s thumbnail is drawn from: the file itself, the app's working copy, or the document. */private fun thumbPathFor(uri: String): String? {val u = Uri.parse(uri)return when (u.scheme) {"file" -> u.path- else -> files.existingCopy(u)?.absolutePath+ else -> files.existingCopy(u)?.absolutePath ?: uri}}@@ -1928,7 +1965,7 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {val stars = recentList.filter { it.starred }.flatMap { listOf(it.uri, sameFile(it.name, it.size)) }.toSet()return localFiles.map { f ->val key = f.uri.toString()- io.github.artcraftandroid.pdfcraft.ui.home.FileRow(key, f.name, f.path, f.folder, f.modified, f.size, key in stars || sameFile(f.name, f.size) in stars) { open(f.uri) }+ io.github.artcraftandroid.pdfcraft.ui.home.FileRow(key, f.name, f.path ?: key, f.folder, f.modified, f.size, key in stars || sameFile(f.name, f.size) in stars) { open(f.uri) }}}diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.ktindex 7c1bc50..6717072 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/HomeScreen.kt@@ -211,8 +211,8 @@ private fun HomeTabScreen(vm: AppViewModel, onBrowse: () -> Unit) {when (tab) {0 -> EmptyState(LucideIcons.Clock, "No recent files", "Files you open will appear here.", "Open file", onBrowse)1 -> EmptyState(LucideIcons.Star, "No starred files", "Star a file from its menu to find it here quickly.")- else -> if (!vm.hasFileAccess) EmptyState(LucideIcons.Smartphone, "Files on your device", "To see the PDFs on this phone, allow access to all files in the Settings.", "Allow access") { vm.requestFileAccess() }- else EmptyState(LucideIcons.Smartphone, "No PDFs on your device", "PDFs you download or save will appear here.")+ else -> if (!vm.hasFileAccess) EmptyState(LucideIcons.Smartphone, "Files on your device", "Choose folders to list PDFs from, such as Documents or a folder inside Download. Files you open from anywhere stay in Recent.", "Add a folder") { vm.requestFileAccess() }+ else EmptyState(LucideIcons.Smartphone, "No PDFs in your folders", "PDFs in the folders you added will appear here.", "Add a folder") { vm.requestFileAccess() }}}} else if (vm.gridView) {diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.ktindex 045bc31..1046230 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/home/Tabs.kt@@ -31,6 +31,7 @@ import androidx.compose.foundation.verticalScrollimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.DropdownMenuimport androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Text@@ -119,16 +120,24 @@ private fun OnThisDevice(vm: AppViewModel) {DropdownMenu(expanded = menu, onDismissRequest = { menu = false }, containerColor = c.surface) {DropdownMenuItem(text = { Text("Sort by name") }, onClick = { sort = 1; menu = false }, trailingIcon = { if (sort == 1) Icon(LucideIcons.Check, null, tint = c.accent) })DropdownMenuItem(text = { Text("Sort by date") }, onClick = { sort = 0; menu = false }, trailingIcon = { if (sort == 0) Icon(LucideIcons.Check, null, tint = c.accent) })+ HorizontalDivider(color = c.divider)+ DropdownMenuItem(text = { Text("Add a folder") }, onClick = { menu = false; vm.requestFileAccess() }, leadingIcon = { Icon(LucideIcons.FolderPlus, null, tint = c.icon) })+ // the folders listed here, each with a way to stop listing it+ for ((tree, name) in vm.localFolders()) {+ DropdownMenuItem(text = { Text("Stop listing $name") }, onClick = { menu = false; vm.removeLocalFolder(tree) }, leadingIcon = { Icon(LucideIcons.Folder, null, tint = c.icon) })+ }}}}- if (!vm.hasFileAccess) {- EmptyState(LucideIcons.Smartphone, "Files on your device", "To list the PDFs on this phone, PdfCraft needs access to all files. Allow it in the Settings.", "Go to settings") { vm.requestFileAccess() }+ val rows = vm.localRows().let { if (sort == 1) it.sortedBy { r -> r.name.lowercase() } else it }+ // what PdfCraft saved itself shows before any folder is added+ if (!vm.hasFileAccess && rows.isEmpty()) {+ EmptyState(LucideIcons.Smartphone, "Files on your device", "Choose folders to list PDFs from, such as Documents or a folder inside Download (Android doesn't let apps list the whole Download folder). PdfCraft sees only the folders you choose, and files you open from anywhere stay in Recent.", "Add a folder") { vm.requestFileAccess() }return@Column}- val rows = vm.localRows().let { if (sort == 1) it.sortedBy { r -> r.name.lowercase() } else it }if (rows.isEmpty()) {- EmptyState(LucideIcons.FileText, if (vm.scanning) "Looking for PDFs…" else "No PDFs on your device", if (vm.scanning) "" else "PDFs you download or save will appear here.")+ if (vm.scanning) EmptyState(LucideIcons.FileText, "Looking for PDFs…", "")+ else EmptyState(LucideIcons.FileText, "No PDFs in your folders", "PDFs in the folders you added will appear here.", "Add a folder") { vm.requestFileAccess() }return@Column}LazyColumn(Modifier.weight(1f)) {@@ -318,8 +327,8 @@ fun SettingsScreen(vm: AppViewModel) {"help" -> {val uri = LocalUriHandler.currentvar leaving by remember { mutableStateOf<String?>(null) }- SheetRow(LucideIcons.CircleHelp, "Help", { leaving = "https://github.com/storytold/pdfcraft#readme" })- SheetRow(LucideIcons.MessageSquare, "Report a problem or request a feature", { leaving = "https://github.com/storytold/pdfcraft/issues" })+ SheetRow(LucideIcons.CircleHelp, "Help", { leaving = "$APP_REPO#readme" })+ SheetRow(LucideIcons.MessageSquare, "Report a problem or request a feature", { leaving = "$APP_REPO/issues" })leaving?.let { url ->io.github.artcraftandroid.pdfcraft.ui.PdfDialog(onDismiss = { leaving = null }, title = "Leaving PdfCraft", confirm = "Continue", onConfirm = { leaving = null; uri.openUri(url) },@@ -352,6 +361,15 @@ private fun Preferences(vm: AppViewModel) {PdfSwitch(vm.keepScreenOn, { vm.updateKeepScreenOn(it) })}Text("Keeps the screen on while you read, for up to 30 minutes without a touch.", color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp))+ SheetDivider()+ Section("Keyboard")+ SheetRow(null, "Keyboard shortcuts", { vm.updateKeyboardShortcuts(!vm.keyboardShortcuts) }) {+ PdfSwitch(vm.keyboardShortcuts, { vm.updateKeyboardShortcuts(it) })+ }+ Text(+ "With a keyboard connected: N or Page Down for the next page, P or Page Up for the previous one, the arrow keys to scroll, Ctrl+P to print, Ctrl and + or − to zoom.",+ color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp),+ )Spacer(Modifier.height(24.dp))if (authorDialog) {var name by remember { mutableStateOf(vm.toolPrefs.author) }@@ -362,6 +380,9 @@ private fun Preferences(vm: AppViewModel) {}}+/** PdfCraft for Android's own repository: its help, its issues and its source. */+private const val APP_REPO = "https://github.com/artcraft-android/pdfcraft-android"+@Composableprivate fun Section(title: String) {Text(title, color = pdfColors.accent, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(start = 20.dp, top = 16.dp, bottom = 4.dp))@@ -383,7 +404,8 @@ private fun About(vm: AppViewModel) {SheetDivider()Section("Legal")SheetRow(null, "Open-source licences", { vm.showLicences = true })- SheetRow(null, "Source code", { uri.openUri("https://github.com/storytold/pdfcraft") })+ SheetRow(null, "Source code", { uri.openUri(APP_REPO) })+ SheetRow(null, "PdfCraft engine", { uri.openUri("https://github.com/storytold/pdfcraft") })Text("PdfCraft for Android is built on PdfCraft's Rust engine. MIT OR Apache-2.0. PdfCraft is not affiliated with Adobe; Acrobat is a trademark of Adobe Inc.",color = c.textSecondary, fontSize = 13.sp, modifier = Modifier.padding(20.dp), overflow = TextOverflow.Visible,diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.ktindex b29f52e..bde8414 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerBars.kt@@ -3,11 +3,14 @@ package io.github.artcraftandroid.pdfcraft.ui.viewerimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectVerticalDragGestures+import androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.offset@@ -15,6 +18,7 @@ import androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.requiredSizeimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthInimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardActionsimport androidx.compose.foundation.text.KeyboardOptions@@ -22,6 +26,7 @@ import androidx.compose.material3.Iconimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.ui.draw.clip+import androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.runtime.getValueimport androidx.compose.runtime.setValueimport androidx.compose.runtime.LaunchedEffect@@ -32,6 +37,8 @@ import androidx.compose.ui.draw.drawBehindimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.geometry.Offset+import androidx.compose.ui.layout.onPlaced+import androidx.compose.ui.layout.positionInParentimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.Pathimport androidx.compose.ui.graphics.SolidColor@@ -53,6 +60,7 @@ import io.github.artcraftandroid.pdfcraft.ui.BarIconimport io.github.artcraftandroid.pdfcraft.ui.Interimport io.github.artcraftandroid.pdfcraft.ui.LucideIconsimport io.github.artcraftandroid.pdfcraft.ui.pdfColors+import kotlinx.coroutines.flow.first/** The viewer's top bar height (the reference's: 56 dp). */val TopBarHeight = 57.dp@@ -260,7 +268,7 @@ private fun QuickItem(icon: ImageVector, label: String, onClick: () -> Unit, subhorizontalAlignment = Alignment.CenterHorizontally,) {Box(- Modifier.size(44.dp).background(if (selected) c.divider else Color.Transparent, androidx.compose.foundation.shape.RoundedCornerShape(4.dp)),+ Modifier.size(44.dp).offset(y = 2.5.dp).background(if (selected) c.divider else Color.Transparent, androidx.compose.foundation.shape.RoundedCornerShape(4.dp)),contentAlignment = Alignment.Center,) {Icon(icon, null, tint = c.icon, modifier = Modifier.size(24.dp))@@ -273,30 +281,95 @@ private fun QuickItem(icon: ImageVector, label: String, onClick: () -> Unit, sub})}}- // the reference's 11 sp face is narrower than Inter, so a half point less matches its width- Text(label, color = c.label, fontSize = 10.5.sp, maxLines = 1, overflow = TextOverflow.Clip, textAlign = TextAlign.Center)+ // the reference's 11 sp face is narrower than Inter: a half point less gives its height, and+ // tighter letters its width; the label sits 2.5 dp nearer the icon than the box's edge+ Text(+ label, color = c.label, fontSize = 10.5.sp, letterSpacing = (-0.5).sp, maxLines = 1, overflow = TextOverflow.Clip, textAlign = TextAlign.Center,+ modifier = Modifier.offset(y = (-2.5).dp),+ )}}-/** The quick toolbar: the tools the user keeps there (the reference's six at first), then More tools. */+/** The strip above the quick toolbar's tools that holds its handle. */+val QuickHandleHeight = 22.dp++/** The quick toolbar's height with its handle, the shortcuts folded away. */+val QuickBarHeight = BottomBarHeight + QuickHandleHeight++/** A shortcut in the row the quick toolbar's handle pulls up. */+class QuickChip(val label: String, val icon: ImageVector, val tint: Color, val onClick: () -> Unit)++/**+ * The quick toolbar: a handle, then the tools the user keeps there (the reference's six at first)+ * and More tools. Pulling the handle up (or tapping it) shows a row of [chips] above the tools,+ * scrolling sideways; pulling it down folds them away. No line along its top, as the reference.+ */@Composablefun QuickToolbar(tools: List<QuickTool>,onTool: (QuickTool) -> Unit,onMoreTools: () -> Unit,moreToolsOpen: Boolean,+ chips: List<QuickChip> = emptyList(),) {- androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxWidth().height(BottomBarHeight).barTopLine().background(pdfColors.surface)) {+ val c = pdfColors+ var open by remember { androidx.compose.runtime.mutableStateOf(false) }+ androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxWidth().background(c.surface)) {val slots = toolbarSlots(androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp)val shown = tools.take(slots)val itemW = minOf(72.dp, (maxWidth - 16.dp) / maxOf(7, shown.size + 1))- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {- for (t in shown) QuickItem(t.icon, t.label, { onTool(t) }, subTools = t.subTools, width = itemW)- QuickItem(LucideIcons.LayoutGrid, "More tools", onMoreTools, selected = moreToolsOpen, width = itemW)+ Column(+ Modifier.fillMaxWidth().pointerInput(chips.isNotEmpty()) {+ if (chips.isEmpty()) return@pointerInput+ var pulled = 0f+ detectVerticalDragGestures(+ onDragStart = { pulled = 0f },+ onDragEnd = { if (pulled < -8f) open = true else if (pulled > 8f) open = false },+ ) { _, dy -> pulled += dy }+ },+ ) {+ Box(+ Modifier.fillMaxWidth().height(QuickHandleHeight)+ .clickable(enabled = chips.isNotEmpty(), role = Role.Button) { open = !open }+ .semantics { contentDescription = if (open) "Hide shortcuts" else "Show shortcuts" },+ contentAlignment = Alignment.TopCenter,+ ) {+ // measured on the dark bar; the light bar's grey is our own match+ val handle = if (c.dark) Color(0xFF6A6A6A) else Color(0xFFC4C4C4)+ Box(Modifier.padding(top = 15.dp).size(40.dp, 4.dp).background(handle, androidx.compose.foundation.shape.RoundedCornerShape(2.dp)))+ }+ androidx.compose.animation.AnimatedVisibility(open && chips.isNotEmpty()) {+ Row(+ Modifier.fillMaxWidth().horizontalScroll(androidx.compose.foundation.rememberScrollState())+ .padding(start = 18.dp, end = 18.dp, top = 5.dp, bottom = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(11.dp),+ ) { for (chip in chips) QuickChipView(chip) }+ }+ Row(Modifier.fillMaxWidth().height(BottomBarHeight), horizontalArrangement = Arrangement.Center) {+ for (t in shown) QuickItem(t.icon, t.label, { onTool(t) }, subTools = t.subTools, width = itemW)+ QuickItem(LucideIcons.LayoutGrid, "More tools", onMoreTools, selected = moreToolsOpen, width = itemW)+ }}}}+/** One shortcut: its coloured icon and name on a dark rounded box, 37 dp tall. */+@Composable+private fun QuickChipView(chip: QuickChip) {+ val c = pdfColors+ val shape = androidx.compose.foundation.shape.RoundedCornerShape(6.dp)+ Row(+ Modifier.height(37.dp).clip(shape).background(if (c.dark) Color(0xFF080808) else Color(0xFFEDEDED))+ .clickable(role = Role.Button, onClick = chip.onClick).padding(start = 7.dp, end = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ // sized against the reference: its icon draws about 18 dp, its name 14 sp in a narrower face+ Icon(chip.icon, null, tint = chip.tint, modifier = Modifier.size(21.dp))+ Spacer(Modifier.width(8.dp))+ Text(chip.label, color = c.text, fontSize = 14.sp, letterSpacing = (-0.65).sp, maxLines = 1)+ }+}+/** The 1 dp line the reference draws along the top of its bottom bars, just above them. */@Composablefun Modifier.barTopLine(): Modifier {@@ -307,14 +380,39 @@ fun Modifier.barTopLine(): Modifier {}}-/** A tool's sub-toolbar: its buttons centred on the bar, groups split by thin lines. */+/**+ * A tool's sub-toolbar: its buttons centred on the bar, groups split by thin lines. As the reference:+ * the buttons keep their size, and when they don't all fit (a narrow screen, a large display size)+ * the bar scrolls sideways, sliding to a tool when it's chosen. (Squeezing the buttons together to+ * fit was tried and left out; see docs/parity-mobile.md, "Tool bars on narrow screens".)+ */@Composablefun SubToolbar(content: @Composable () -> Unit) {- Row(- Modifier.fillMaxWidth().height(BottomBarHeight).barTopLine().background(pdfColors.surface),- horizontalArrangement = Arrangement.Center,- verticalAlignment = Alignment.CenterVertically,- ) { content() }+ val scroll = androidx.compose.foundation.rememberScrollState()+ androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxWidth().height(BottomBarHeight).barTopLine().background(pdfColors.surface)) {+ Row(+ Modifier.fillMaxHeight().horizontalScroll(scroll).widthIn(min = maxWidth),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically,+ ) { androidx.compose.runtime.CompositionLocalProvider(LocalSubToolbarScroll provides scroll) { content() } }+ }+}++/** The scrolling bar a sub-toolbar tool sits in (none outside one). */+private val LocalSubToolbarScroll = androidx.compose.runtime.staticCompositionLocalOf<androidx.compose.foundation.ScrollState?> { null }++/** When the tool becomes the chosen one, the bar scrolls to bring it to the start (as far as it goes). */+@Composable+private fun Modifier.slideToWhenChosen(selected: Boolean): Modifier {+ val scroll = LocalSubToolbarScroll.current ?: return this+ var x by remember { androidx.compose.runtime.mutableStateOf<Int?>(null) }+ LaunchedEffect(selected) {+ if (!selected) return@LaunchedEffect+ // once the tool has been placed on the bar+ val at = androidx.compose.runtime.snapshotFlow { x }.first { it != null } ?: return@LaunchedEffect+ scroll.animateScrollTo(at)+ }+ return onPlaced { x = it.positionInParent().x.toInt() }}/** A sub-toolbar tool: 62 dp apart, as the reference spaces them. */@@ -328,7 +426,7 @@ fun SubTool(icon: ImageVector, description: String, selected: Boolean, onClick:fun SubTextField(description: String, selected: Boolean, onClick: () -> Unit) {val tint = if (selected) pdfColors.toolAccent else pdfColors.iconBox(- Modifier.width(62.dp).height(54.dp).clickable(role = Role.Button, onClick = onClick).semantics { contentDescription = description },+ Modifier.width(62.dp).height(54.dp).slideToWhenChosen(selected).clickable(role = Role.Button, onClick = onClick).semantics { contentDescription = description },contentAlignment = Alignment.Center,) {Box(@@ -349,7 +447,7 @@ fun SubTextField(description: String, selected: Boolean, onClick: () -> Unit) {fun SubDot(description: String, selected: Boolean, onClick: () -> Unit) {val tint = if (selected) pdfColors.toolAccent else pdfColors.iconBox(- Modifier.width(62.dp).height(54.dp).clickable(role = Role.Button, onClick = onClick).semantics { contentDescription = description },+ Modifier.width(62.dp).height(54.dp).slideToWhenChosen(selected).clickable(role = Role.Button, onClick = onClick).semantics { contentDescription = description },contentAlignment = Alignment.Center,) { Box(Modifier.size(8.dp).background(tint, androidx.compose.foundation.shape.CircleShape)) }}@@ -365,7 +463,7 @@ private fun SubButton(icon: ImageVector, description: String, selected: Boolean,val c = pdfColorsval tint = if (selected && !shaded) c.toolAccent else c.iconBox(- Modifier.width(width).height(54.dp).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = description },+ Modifier.width(width).height(54.dp).slideToWhenChosen(selected && !shaded).clickable(enabled = enabled, role = Role.Button, onClick = onClick).semantics { contentDescription = description },contentAlignment = Alignment.Center,) {if (shaded && selected) Box(Modifier.requiredSize(40.dp).background(c.pressed, androidx.compose.foundation.shape.RoundedCornerShape(5.dp)))diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.ktindex 618dc9e..10549e8 100644--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/viewer/ViewerScreen.kt@@ -106,7 +106,7 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {val statusPx = maxOf(WindowInsets.statusBars.getTop(density), WindowInsets.displayCutout.getTop(density)).toFloat()val navPx = WindowInsets.navigationBars.getBottom(density).toFloat()val topPx = with(density) { TopBarHeight.toPx() }- val bottomPx = with(density) { BottomBarHeight.toPx() }+ val bottomPx = with(density) { (if (ctl.tool == ViewerTool.None) QuickBarHeight else BottomBarHeight).toPx() }// keyed on the document too: one opened over another (Create, Combine) has a fresh page viewLaunchedEffect(doc, ctl.barsVisible, statusPx, navPx, ctl.searching, ctl.tool, vm.readingMode) {val bottomShown = ctl.barsVisible && !ctl.searching && !vm.readingMode@@ -356,6 +356,12 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {onTool = { vm.runQuickTool(doc, it) },onMoreTools = { ctl.sheet = if (ctl.sheet == ViewerSheet.MoreTools) ViewerSheet.None else ViewerSheet.MoreTools },moreToolsOpen = ctl.sheet == ViewerSheet.MoreTools,+ chips = listOf(+ QuickChip(if (vm.isStarred(doc)) "Unstar this file" else "Star this file", LucideIcons.Star, ToolHues.combine) { vm.toggleStar(doc) },+ QuickChip("Read aloud", LucideIcons.Headphones, ToolHues.read) { vm.startReadAloud(doc) },+ QuickChip("Create PDF", QuickTool.Create.icon, ToolHues.create) { vm.runQuickTool(doc, QuickTool.Create) },+ QuickChip("Organize pages", QuickTool.Organize.icon, ToolHues.organize) { vm.runQuickTool(doc, QuickTool.Organize) },+ ),)} else {ToolSubToolbar(vm, doc)