camera: fix Save location for SAF tree folders
- Commit
3108e1d19166ae3f676a1aada489a6c8d465563e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 21:42 UTC (1 day ago)
- Parents
9726987
The Save location setting appeared stuck on DCIM/Camera for any folder chosen inside DCIM or Pictures. The picked folder arrives as a SAF tree URI, but SafDocuments used that bare tree URI for document operations: displayName queried it directly (a bare tree URI matches no DocumentsProvider route, only tree/*/document/* does, so the query failed and the settings row fell back to the default label), and createDocument passed it as the parent document (DocumentsProvider extracts the parent with getDocumentId, which rejects a bare tree URI, so every SAF capture fell back to MediaStore DCIM/Camera). Fix SafDocuments to convert the tree URI to the tree root's document URI (buildDocumentUriUsingTree) for display-name queries and document creation, fall back to the document-id leaf name when a provider cannot be queried, and canonicalize a picked document-form URI to its tree form before persisting. Match the persisted grant on authority plus document id instead of exact Uri equality, take only the read/write modes the picker actually granted in SettingsPage, and request the prefix grant for the chosen tree. Add CameraSaveLocationTreeUriTest against a filesystem-backed DocumentsProvider: the display name, in-tree creation, and document-URI normalization cases fail on the previous code and pass now. Update SafPrepareExtraTest for the leaf-name fallback. Verified in the worktree with ./gradlew :camera:lint :camera:lintVitalRelease :camera:testDevUnitTest (BUILD SUCCESSFUL).
Diff
camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.ktindex f9d709c861..bf401908cf 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSaveLocation.kt@@ -37,7 +37,8 @@ internal fun CameraViewModel.loadSaveTarget() { return } val uriString = ds.getString(KEY_SAVE_TREE_URI)- val uri = uriString?.takeIf { it.isNotBlank() }?.let { runCatching { it.toUri() }.getOrNull() }+ val uri = uriString?.takeIf { it.isNotBlank() }+ ?.let { runCatching { SafDocuments.asTreeUri(it.toUri()) }.getOrNull() } if (uri != null && SafDocuments.hasPersistedPermission(app.contentResolver, uri)) { saveTargetMutable.value = SaveTarget.SafTree(uri) } else {@@ -52,9 +53,13 @@ internal fun CameraViewModel.loadSaveTarget() { /** Persists a newly picked SAF tree (permission must already be taken by the caller). */ fun CameraViewModel.setSaveTreeUri(uri: Uri) {- saveTargetMutable.value = SaveTarget.SafTree(uri)+ // Some pickers hand back the tree root's document URI instead of a+ // tree URI; persist the tree form so every later lookup (tree+ // document id, relative path, permission match) sees one shape.+ val treeUri = SafDocuments.asTreeUri(uri)+ saveTargetMutable.value = SaveTarget.SafTree(treeUri) viewModelScope.launch {- ds.setString(KEY_SAVE_TREE_URI, uri.toString())+ ds.setString(KEY_SAVE_TREE_URI, treeUri.toString()) ds.setString(KEY_SAVE_MODE, MODE_SAF) } }@@ -70,19 +75,73 @@ fun CameraViewModel.clearSaveTreeUri() { /** DocumentFile-free SAF helpers built on DocumentsContract + ContentResolver. */ object SafDocuments {- fun hasPersistedPermission(resolver: android.content.ContentResolver, treeUri: Uri): Boolean =- resolver.persistedUriPermissions.any {- it.uri == treeUri && it.isReadPermission && it.isWritePermission+ /**+ * The tree form of [uri]: a tree URI passes through, a document URI+ * for a folder (what some pickers return for a tree pick) is rebuilt+ * as the tree URI for the same document, anything else is unchanged.+ */+ fun asTreeUri(uri: Uri): Uri {+ val authority = uri.authority ?: return uri+ // A tree URI, a tree/document URI for the tree root, and a plain+ // document URI all name the same folder; canonicalize to the+ // plain tree form.+ val docId = treeDocumentId(uri) ?: return uri+ return DocumentsContract.buildTreeDocumentUri(authority, docId)+ }++ /**+ * The document URI for [treeUri]'s root. Document operations must+ * use this form: a bare tree URI matches no DocumentsProvider query+ * route (`tree/*/document/*` only) and `getDocumentId` rejects+ * it, so querying or creating with the tree URI itself always fails.+ */+ fun documentUri(treeUri: Uri): Uri {+ if (!runCatching { DocumentsContract.isTreeUri(treeUri) }.getOrDefault(false)) return treeUri+ val docId = runCatching { DocumentsContract.getTreeDocumentId(treeUri) }.getOrNull()+ ?: return treeUri+ return DocumentsContract.buildDocumentUriUsingTree(treeUri, docId)+ }++ /** Tree-root document id of [uri] in tree or document form, else null. */+ fun treeDocumentId(uri: Uri): String? =+ if (runCatching { DocumentsContract.isTreeUri(uri) }.getOrDefault(false)) {+ runCatching { DocumentsContract.getTreeDocumentId(uri) }.getOrNull()+ } else {+ runCatching { DocumentsContract.getDocumentId(uri) }.getOrNull() } - fun takePersistablePermission(resolver: android.content.ContentResolver, treeUri: Uri) {- try {- resolver.takePersistableUriPermission(- treeUri,- Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,- )+ fun hasPersistedPermission(resolver: android.content.ContentResolver, treeUri: Uri): Boolean {+ // Match on authority + document id, not Uri equality: a grant+ // persisted from the picker's document-form URI (or a URI that+ // differs only in encoding/user-id) is the same folder, and an+ // equality check silently dropped it and reset the setting.+ // Write is the permission capture needs; the folder name falls+ // back to the document-id leaf, so read is not required here.+ val wantedId = treeDocumentId(treeUri) ?: return false+ return resolver.persistedUriPermissions.any {+ it.isWritePermission && it.uri.authority == treeUri.authority &&+ treeDocumentId(it.uri) == wantedId+ }+ }++ /**+ * Takes the persistable grant for [uri]; [modeFlags] must be the+ * read/write modes the picker actually granted (asking for a mode+ * that was not granted throws and the folder is lost). Returns+ * whether a write grant was taken.+ */+ fun takePersistablePermission(+ resolver: android.content.ContentResolver,+ treeUri: Uri,+ modeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,+ ): Boolean {+ if (modeFlags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION == 0) return false+ return try {+ resolver.takePersistableUriPermission(treeUri, modeFlags)+ true } catch (e: SecurityException) { Log.status("SafDocuments", "takePersistableUriPermission failed for $treeUri", e)+ false } } @@ -111,8 +170,8 @@ object SafDocuments { mimeType: String, displayName: String, ): Uri? = try {- DocumentsContract.createDocument(resolver, treeUri, mimeType, displayName)- } catch (e: IllegalArgumentException) {+ DocumentsContract.createDocument(resolver, documentUri(treeUri), mimeType, displayName)+ } catch (e: RuntimeException) { Log.status("SafDocuments", "createDocument failed for $displayName", e) null } catch (e: java.io.FileNotFoundException) {@@ -121,18 +180,25 @@ object SafDocuments { } /** Human-readable folder name for the settings row, e.g. "TestCam". */- fun displayName(resolver: android.content.ContentResolver, treeUri: Uri): String? = try {- resolver.query(treeUri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->- if (c.moveToFirst()) c.getString(0) else null+ fun displayName(resolver: android.content.ContentResolver, treeUri: Uri): String? {+ val queried = try {+ resolver.query(documentUri(treeUri), arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)+ ?.use { c -> if (c.moveToFirst()) c.getString(0) else null }+ } catch (e: RuntimeException) {+ Log.status("SafDocuments", "displayName query failed for $treeUri", e)+ null }- } catch (e: SecurityException) {- Log.status("SafDocuments", "displayName query failed for $treeUri", e)- null- } catch (e: IllegalArgumentException) {- Log.status("SafDocuments", "displayName query failed for $treeUri", e)- null+ // A provider that cannot be queried still leaves the folder+ // identifiable from its document id ("primary:Pictures/TestCam");+ // returning null made the settings row show the default instead.+ return queried?.takeIf { it.isNotBlank() } ?: leafName(treeUri) } + /** Last path segment of [uri]'s document id, e.g. "TestCam". */+ fun leafName(treeUri: Uri): String? =+ treeDocumentId(treeUri)?.substringAfter(':', "")?.trim('/')?.substringAfterLast('/')+ ?.takeIf { it.isNotBlank() }+ /** * Best-effort absolute path when the tree lives on primary external storage * (e.g. `/storage/emulated/0/Pictures/TestCam`), for media-scan indexing.
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex a234fc2a35..8da4906544 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -130,13 +130,14 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM ) { result -> val treeUri: Uri? = result.data?.data if (result.resultCode == android.app.Activity.RESULT_OK && treeUri != null) {- try {- context.contentResolver.takePersistableUriPermission(- treeUri,- Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,- )+ // Take only the modes the picker actually granted (an ungranted+ // mode throws and the pick is dropped), on the URI as returned;+ // setSaveTreeUri stores its tree form.+ val rw = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ val modeFlags = (result.data?.flags?.and(rw) ?: 0).takeIf { it != 0 } ?: rw+ if (SafDocuments.takePersistablePermission(context.contentResolver, treeUri, modeFlags)) { viewModel.setSaveTreeUri(treeUri)- } catch (_: Exception) {+ } else { messenger.show(saveLocationError) } }@@ -169,7 +170,8 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or- Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION,+ Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or+ Intent.FLAG_GRANT_PREFIX_URI_PERMISSION, ) } runCatching { folderPicker.launch(intent) }
camera/src/test/java/com/vayunmathur/camera/data/CameraSaveLocationTreeUriTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/data/CameraSaveLocationTreeUriTest.kt b/camera/src/test/java/com/vayunmathur/camera/data/CameraSaveLocationTreeUriTest.ktnew file mode 100644index 0000000000..b93b53f766--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/data/CameraSaveLocationTreeUriTest.kt@@ -0,0 +1,207 @@+package com.vayunmathur.camera.data++import android.content.ContentResolver+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.Bundle+import android.os.CancellationSignal+import android.os.ParcelFileDescriptor+import android.provider.DocumentsContract+import android.provider.DocumentsProvider+import androidx.test.core.app.ApplicationProvider+import java.io.File+import java.io.FileNotFoundException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowContentResolver++/**+ * Tree-URI handling for the Save location setting, against a real+ * [DocumentsProvider]: a picked folder arrives as a *tree* URI+ * (`.../tree/primary%3APictures%2FTestCam`), while document operations+ * (query for the display name, createDocument for a capture) need the+ * *document* URI for the tree root (`.../tree/.../document/...`).+ * Passing the bare tree URI to either fails on the platform provider+ * (its URI matcher only routes `tree/*/document/*`, and+ * `getDocumentId` rejects a bare tree URI), so the setting read back as+ * the default and every SAF capture fell back to MediaStore.+ */+@Implements(ContentResolver::class)+class CameraDocsContentResolverShadow : ShadowContentResolver() {+ @Implementation+ override fun query(+ uri: Uri,+ projection: Array<String>?,+ selection: String?,+ selectionArgs: Array<String>?,+ sortOrder: String?,+ ): Cursor? {+ val provider = FakeTreeDocumentsProvider.instance+ if (provider != null && uri.authority == FakeTreeDocumentsProvider.AUTHORITY) {+ return provider.query(uri, projection, Bundle(), null)+ }+ return super.query(uri, projection, selection, selectionArgs, sortOrder)+ }+}++/** Filesystem-backed provider whose root document is `Pictures/TestCam`. */+class FakeTreeDocumentsProvider : DocumentsProvider() {+ override fun onCreate(): Boolean {+ instance = this+ return true+ }++ override fun isChildDocument(parentDocId: String, docId: String): Boolean =+ docId == parentDocId || docId.startsWith("$parentDocId/")++ private fun file(docId: String): File = when {+ docId == ROOT_ID -> rootDir+ docId.startsWith("$ROOT_ID/") -> File(rootDir, docId.removePrefix("$ROOT_ID/"))+ else -> throw FileNotFoundException(docId)+ }++ private fun docId(file: File): String =+ if (file == rootDir) {+ ROOT_ID+ } else {+ "$ROOT_ID/" + file.relativeTo(rootDir).path.replace(File.separatorChar, '/')+ }++ override fun queryRoots(projection: Array<out String>?): Cursor {+ val cols = projection?.toList() ?: listOf(DocumentsContract.Root.COLUMN_ROOT_ID)+ val cursor = MatrixCursor(cols.toTypedArray())+ cursor.newRow().add(ROOT_ID)+ return cursor+ }++ override fun queryDocument(documentId: String, projection: Array<out String>?): Cursor {+ val cols = projection?.toList() ?: listOf(+ DocumentsContract.Document.COLUMN_DOCUMENT_ID,+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,+ )+ val cursor = MatrixCursor(cols.toTypedArray())+ val target = file(documentId)+ if (target.exists()) {+ val row = cursor.newRow()+ for (col in cols) {+ row.add(+ when (col) {+ DocumentsContract.Document.COLUMN_DOCUMENT_ID -> docId(documentId.let { target })+ DocumentsContract.Document.COLUMN_DISPLAY_NAME ->+ if (target == rootDir) "TestCam" else target.name+ DocumentsContract.Document.COLUMN_MIME_TYPE ->+ if (target.isDirectory) DocumentsContract.Document.MIME_TYPE_DIR else "image/jpeg"+ else -> 0+ },+ )+ }+ }+ return cursor+ }++ override fun queryChildDocuments(+ parentDocumentId: String,+ projection: Array<out String>?,+ sortOrder: String?,+ ): Cursor = MatrixCursor(arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID))++ override fun createDocument(parentDocumentId: String, mimeType: String, displayName: String): String {+ val parent = file(parentDocumentId)+ parent.mkdirs()+ val target = File(parent, displayName)+ if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) target.mkdirs() else target.createNewFile()+ return docId(target)+ }++ override fun openDocument(+ documentId: String,+ mode: String,+ signal: CancellationSignal?,+ ): ParcelFileDescriptor {+ val target = file(documentId)+ if (!target.exists() && mode.contains("w")) {+ target.parentFile?.mkdirs()+ target.createNewFile()+ }+ if (!target.exists()) throw FileNotFoundException(documentId)+ return ParcelFileDescriptor.open(target, ParcelFileDescriptor.parseMode(mode))+ }++ companion object {+ var instance: FakeTreeDocumentsProvider? = null+ const val AUTHORITY = "com.vayunmathur.camera.fakedocs"+ const val ROOT_ID = "primary:Pictures/TestCam"+ lateinit var rootDir: File+ }+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [CameraDocsContentResolverShadow::class])+class CameraSaveLocationTreeUriTest {+ private val context: Context get() = ApplicationProvider.getApplicationContext()+ private val resolver get() = context.contentResolver+ private val treeUri: Uri =+ DocumentsContract.buildTreeDocumentUri(FakeTreeDocumentsProvider.AUTHORITY, FakeTreeDocumentsProvider.ROOT_ID)++ @Before fun setUp() {+ FakeTreeDocumentsProvider.rootDir =+ File(context.cacheDir, "saf-tree-${System.nanoTime()}").apply { mkdirs() }+ val provider = FakeTreeDocumentsProvider()+ provider.attachInfo(+ context,+ android.content.pm.ProviderInfo().apply {+ authority = FakeTreeDocumentsProvider.AUTHORITY+ exported = true+ grantUriPermissions = true+ readPermission = android.Manifest.permission.MANAGE_DOCUMENTS+ writePermission = android.Manifest.permission.MANAGE_DOCUMENTS+ },+ )+ try {+ val method = Class.forName("org.robolectric.shadows.ShadowContentResolver")+ .getMethod(+ "registerProviderInternal",+ String::class.java,+ android.content.ContentProvider::class.java,+ )+ method.invoke(null, FakeTreeDocumentsProvider.AUTHORITY, provider)+ } catch (e: Exception) {+ val shadow = Shadows.shadowOf(resolver)+ val method = shadow.javaClass.methods.first { it.name.contains("registerProvider") }+ method.invoke(shadow, FakeTreeDocumentsProvider.AUTHORITY, provider)+ }+ }++ @Test fun displayNameResolvesForTreeUri() {+ assertEquals("TestCam", SafDocuments.displayName(resolver, treeUri))+ }++ @Test fun createImageDocCreatesInsideTreeRoot() {+ val created = SafDocuments.createImageDoc(resolver, treeUri, "IMG_0001.jpg")+ assertNotNull(created)+ assertTrue(File(FakeTreeDocumentsProvider.rootDir, "IMG_0001.jpg").isFile)+ }++ @Test fun pickedDocumentUriIsStoredAsTreeUri() {+ // Some pickers hand back the root *document* URI for the chosen+ // folder instead of a tree URI; the setting must still persist+ // (and later resolve) it as the tree.+ val documentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, FakeTreeDocumentsProvider.ROOT_ID)+ val viewModel = com.vayunmathur.camera.platform.CameraViewModel(+ context.applicationContext as android.app.Application,+ )+ viewModel.setSaveTreeUri(documentUri)+ assertEquals(SaveTarget.SafTree(treeUri), viewModel.saveTargetMutable.value)+ }+}
camera/src/test/java/com/vayunmathur/camera/data/SafPrepareExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/data/SafPrepareExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/data/SafPrepareExtraTest.ktindex 8765512abc..165a898009 100644--- a/camera/src/test/java/com/vayunmathur/camera/data/SafPrepareExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/data/SafPrepareExtraTest.kt@@ -37,7 +37,9 @@ class SafPrepareExtraTest { assertNull(SafDocuments.createVideoDoc(context.contentResolver, tree, "x.mp4")) assertEquals(false, SafDocuments.hasPersistedPermission(context.contentResolver, tree)) SafDocuments.takePersistablePermission(context.contentResolver, tree)- assertNull(SafDocuments.displayName(context.contentResolver, tree))+ // No provider behind this tree: the name falls back to the+ // document-id leaf instead of null (which showed as the default).+ assertEquals("Pictures", SafDocuments.displayName(context.contentResolver, tree)) } @Test fun safPrimaryPathParsing() { val primary = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3APictures%2FTestCam")