Modern Apps git

← Modern-Apps.git

files: add system SAF document picker

Commit
af174447a861d7f50e2c5f15f96c71d87a6ddf60
Author
Vayun Mathur <[email protected]>
When
2026-08-09 04:59 UTC (3 months ago)
Parents
449019c

Diff

files/src/main/AndroidManifest.xml
diff --git a/files/src/main/AndroidManifest.xml b/files/src/main/AndroidManifest.xmlindex 2acf2c0805..21ffaf70ed 100644--- a/files/src/main/AndroidManifest.xml+++ b/files/src/main/AndroidManifest.xml@@ -7,8 +7,13 @@     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+    <!-- Signature|privileged. Granted only when Files ships as the system documents UI (MAOS);+         ignored on a normal install. Lets the SAF picker return/persist provider-backed URIs. -->+    <uses-permission android:name="android.permission.MANAGE_DOCUMENTS"+        tools:ignore="ProtectedPermissions" />      <application+        android:name=".FilesApp"         android:allowBackup="true"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"@@ -58,6 +63,37 @@             </intent-filter>         </activity> +        <!-- Storage Access Framework picker. Files takes over DocumentsUI's SAF role, but+             ONLY when it is the privileged system documents UI. Ships DISABLED so it never+             appears (e.g. in GET_CONTENT choosers) on a normal install; FilesApp enables it+             at startup iff MANAGE_DOCUMENTS is granted. The OPEN_DOCUMENT / CREATE_DOCUMENT /+             OPEN_DOCUMENT_TREE actions are only ever routed by the framework to the configured+             documents UI package, so they are inert elsewhere regardless. -->+        <activity+            android:name=".saf.DocumentPickerActivity"+            android:enabled="false"+            android:exported="true"+            android:excludeFromRecents="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.OPEN_DOCUMENT" />+                <action android:name="android.intent.action.CREATE_DOCUMENT" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.OPENABLE" />+                <data android:mimeType="*/*" />+            </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.OPEN_DOCUMENT_TREE" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.GET_CONTENT" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.OPENABLE" />+                <data android:mimeType="*/*" />+            </intent-filter>+        </activity>+         <service             android:name="androidx.work.impl.foreground.SystemForegroundService"             android:foregroundServiceType="dataSync"
files/src/main/java/com/vayunmathur/files/FilesApp.kt
diff --git a/files/src/main/java/com/vayunmathur/files/FilesApp.kt b/files/src/main/java/com/vayunmathur/files/FilesApp.ktnew file mode 100644index 0000000000..9dda8d3a0c--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/FilesApp.kt@@ -0,0 +1,43 @@+package com.vayunmathur.files++import android.app.Application+import android.content.ComponentName+import android.content.pm.PackageManager+import com.vayunmathur.files.saf.DocumentPickerActivity++/**+ * Toggles the SAF [DocumentPickerActivity] on exactly when Files is acting as the system+ * documents UI.+ *+ * The picker is declared `android:enabled="false"` so a normal (F-Droid / userspace) install+ * behaves identically to before — it never shows up in `GET_CONTENT` choosers and holds no+ * privileged role. When Files is shipped as the privileged system documents UI (MAOS), the+ * platform grants it `MANAGE_DOCUMENTS`; we detect that here and enable the component so it can+ * service `OPEN_DOCUMENT` / `CREATE_DOCUMENT` / `OPEN_DOCUMENT_TREE` / `GET_CONTENT`.+ *+ * The call is idempotent, so running it on every process start is cheap.+ */+class FilesApp : Application() {+    override fun onCreate() {+        super.onCreate()+        syncDocumentPickerAvailability()+    }++    private fun syncDocumentPickerAvailability() {+        val privileged = checkSelfPermission(android.Manifest.permission.MANAGE_DOCUMENTS) ==+            PackageManager.PERMISSION_GRANTED+        val target = if (privileged) {+            PackageManager.COMPONENT_ENABLED_STATE_ENABLED+        } else {+            PackageManager.COMPONENT_ENABLED_STATE_DISABLED+        }+        val component = ComponentName(this, DocumentPickerActivity::class.java)+        if (packageManager.getComponentEnabledSetting(component) != target) {+            packageManager.setComponentEnabledSetting(+                component,+                target,+                PackageManager.DONT_KILL_APP,+            )+        }+    }+}
files/src/main/java/com/vayunmathur/files/saf/DocumentPickerActivity.kt
diff --git a/files/src/main/java/com/vayunmathur/files/saf/DocumentPickerActivity.kt b/files/src/main/java/com/vayunmathur/files/saf/DocumentPickerActivity.ktnew file mode 100644index 0000000000..003311b085--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/saf/DocumentPickerActivity.kt@@ -0,0 +1,350 @@+package com.vayunmathur.files.saf++import android.content.ClipData+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.BackHandler+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.files.R+import com.vayunmathur.files.util.FileBrowserItem+import com.vayunmathur.files.util.FilesViewModel+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconBack+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.IconFile+import com.vayunmathur.library.ui.IconFolder+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TextField+import com.vayunmathur.library.ui.TopAppBar+import androidx.compose.ui.graphics.Color+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File++/**+ * The system Storage Access Framework picker, standing in for DocumentsUI when Files is the+ * privileged system documents UI (MAOS). Reuses [FilesViewModel] for browsing and returns+ * ExternalStorageProvider-backed URIs (see [StorageUris]) so results are queryable and, when+ * privileged, persistable.+ *+ * Handles OPEN_DOCUMENT, GET_CONTENT, OPEN_DOCUMENT_TREE and CREATE_DOCUMENT. The component is+ * disabled on non-privileged installs (see FilesApp), so this never runs there.+ */+class DocumentPickerActivity : ComponentActivity() {++    private enum class Mode { OPEN, GET_CONTENT, TREE, CREATE }++    private val vm: FilesViewModel by viewModels()++    private lateinit var mode: Mode+    private var allowMultiple = false+    private var mimeFilters: List<String> = emptyList()+    private var initialName: String = "untitled"++    /** True when Files holds MANAGE_DOCUMENTS, i.e. it is the system documents UI. */+    private val privileged: Boolean+        get() = checkSelfPermission(android.Manifest.permission.MANAGE_DOCUMENTS) ==+            PackageManager.PERMISSION_GRANTED++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)++        mode = when (intent?.action) {+            Intent.ACTION_OPEN_DOCUMENT -> Mode.OPEN+            Intent.ACTION_GET_CONTENT -> Mode.GET_CONTENT+            Intent.ACTION_OPEN_DOCUMENT_TREE -> Mode.TREE+            Intent.ACTION_CREATE_DOCUMENT -> Mode.CREATE+            else -> {+                setResult(RESULT_CANCELED)+                finish()+                return+            }+        }+        allowMultiple = (mode == Mode.OPEN || mode == Mode.GET_CONTENT) &&+            intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)+        // EXTRA_MIME_TYPES wins over the bare type when present, matching SAF semantics.+        mimeFilters = intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)?.toList()+            ?: intent.type?.let { listOf(it) }+            ?: emptyList()+        initialName = intent.getStringExtra(Intent.EXTRA_TITLE)?.takeIf { it.isNotBlank() } ?: "untitled"++        enableEdgeToEdge()+        setContent { DynamicTheme { PickerRoot() } }+    }++    @Composable+    private fun PickerRoot() {+        val granted by vm.isFilesGranted.collectAsState()+        LaunchedEffect(granted) { if (granted) vm.openInternalStorage() }+        if (!granted) {+            Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+                Text(stringResource(R.string.grant_all_files_access))+            }+            return+        }+        PickerContent()+    }++    @OptIn(ExperimentalMaterial3Api::class)+    @Composable+    private fun PickerContent() {+        val currentDir by vm.currentDirectory.collectAsState()+        val entries by vm.entries.collectAsState()+        val (dirs, files) = entries+        val root = vm.rootDirectory++        val visibleFiles = remember(files, mode) {+            if (mode == Mode.TREE) emptyList()+            else files.filter { it.realFile?.let { f -> StorageUris.matchesMime(f, mimeFilters) } == true }+        }++        val selected = remember { mutableStateMapOf<String, File>() }+        var createName by remember { mutableStateOf(initialName) }++        val atRoot = currentDir.absolutePath == root.absolutePath+        fun navUp() {+            if (atRoot) cancel() else vm.navigateTo(currentDir.parentFile ?: root)+        }+        BackHandler { navUp() }++        Scaffold(+            modifier = Modifier.imePadding(),+            topBar = {+                TopAppBar(+                    navigationIcon = { com.vayunmathur.library.ui.IconButton(onClick = { navUp() }) { IconBack() } },+                    title = { Text(titleFor(mode)) },+                )+            },+        ) { padding ->+            Column(Modifier.fillMaxSize().padding(padding)) {+                Text(+                    text = currentDir.absolutePath,+                    style = MaterialTheme.typography.labelMedium,+                    color = MaterialTheme.colorScheme.outline,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+                )+                HorizontalDivider()++                LazyColumn(Modifier.weight(1f).fillMaxWidth()) {+                    items(dirs, key = { "d:" + it.key }) { dir ->+                        PickerRow(+                            item = dir,+                            checked = false,+                            onClick = { dir.realFile?.let { vm.navigateTo(it) } },+                        )+                        HorizontalDivider(thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant)+                    }+                    items(visibleFiles, key = { "f:" + it.key }) { file ->+                        PickerRow(+                            item = file,+                            checked = selected.containsKey(file.key),+                            onClick = {+                                val f = file.realFile+                                if (f != null) {+                                    if (allowMultiple) {+                                        if (selected.containsKey(file.key)) selected.remove(file.key)+                                        else selected[file.key] = f+                                    } else {+                                        returnFiles(listOf(f))+                                    }+                                }+                            },+                        )+                        HorizontalDivider(thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant)+                    }+                }++                BottomBar(+                    mode = mode,+                    selectedCount = selected.size,+                    createName = createName,+                    onCreateNameChange = { createName = it },+                    onUseFolder = { returnTree(currentDir) },+                    onConfirmSelection = { returnFiles(selected.values.toList()) },+                    onCreate = { createAndReturn(currentDir, createName) },+                    onCancel = { cancel() },+                )+            }+        }+    }++    @Composable+    private fun PickerRow(item: FileBrowserItem, checked: Boolean, onClick: () -> Unit) {+        Box(Modifier.fillMaxWidth().clickable(onClick = onClick)) {+            ListItem(+                content = { Text(item.name.ifEmpty { "/" }) },+                leadingContent = { if (item.isDirectory) IconFolder() else IconFile() },+                trailingContent = { if (checked) IconCheck() },+                colors = ListItemDefaults.colors(containerColor = Color.Transparent),+            )+        }+    }++    @Composable+    private fun BottomBar(+        mode: Mode,+        selectedCount: Int,+        createName: String,+        onCreateNameChange: (String) -> Unit,+        onUseFolder: () -> Unit,+        onConfirmSelection: () -> Unit,+        onCreate: () -> Unit,+        onCancel: () -> Unit,+    ) {+        // A single tap already returns in single-open mode, so no confirm bar is needed there.+        val needsBar = mode == Mode.TREE || mode == Mode.CREATE || allowMultiple+        if (!needsBar) return+        Surface(color = MaterialTheme.colorScheme.surfaceVariant) {+            Row(+                Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),+                verticalAlignment = Alignment.CenterVertically,+                horizontalArrangement = Arrangement.spacedBy(8.dp),+            ) {+                when (mode) {+                    Mode.CREATE -> {+                        TextField(+                            value = createName,+                            onValueChange = onCreateNameChange,+                            label = { Text(stringResource(R.string.file_name_label)) },+                            singleLine = true,+                            modifier = Modifier.weight(1f),+                        )+                        Button(onClick = onCreate, enabled = createName.isNotBlank()) {+                            Text(stringResource(R.string.saf_save))+                        }+                    }+                    Mode.TREE -> {+                        TextButton(onClick = onCancel) { Text(stringResource(com.vayunmathur.library.ui.R.string.cancel)) }+                        Box(Modifier.weight(1f))+                        Button(onClick = onUseFolder) { Text(stringResource(R.string.saf_use_this_folder)) }+                    }+                    else -> {+                        TextButton(onClick = onCancel) { Text(stringResource(com.vayunmathur.library.ui.R.string.cancel)) }+                        Box(Modifier.weight(1f))+                        Button(onClick = onConfirmSelection, enabled = selectedCount > 0) {+                            Text(stringResource(R.string.saf_select_count, selectedCount))+                        }+                    }+                }+            }+        }+    }++    private fun titleFor(mode: Mode): String = getString(+        when (mode) {+            Mode.CREATE -> R.string.saf_title_create+            Mode.TREE -> R.string.saf_title_tree+            else -> R.string.saf_title_open+        }+    )++    // ---- Result plumbing ----++    private fun uriForFile(file: File): Uri? =+        if (privileged) StorageUris.documentUriFor(this, file) ?: StorageUris.fileProviderUriFor(this, file)+        else StorageUris.fileProviderUriFor(this, file)++    private fun returnFiles(fileList: List<File>) {+        val uris = fileList.mapNotNull { uriForFile(it) }+        if (uris.isEmpty()) { cancel(); return }+        val persistable = privileged && mode != Mode.GET_CONTENT+        finishWithResult(uris, write = false, persistable = persistable)+    }++    private fun returnTree(dir: File) {+        val uri = if (privileged) StorageUris.treeUriFor(this, dir) else null+        if (uri == null) { cancel(); return }+        finishWithResult(listOf(uri), write = true, persistable = privileged)+    }++    private fun createAndReturn(dir: File, rawName: String) {+        val name = rawName.trim().ifEmpty { return }+        lifecycleScope.launch {+            val file = withContext(Dispatchers.IO) {+                val target = uniqueChild(dir, name)+                runCatching { target.parentFile?.mkdirs(); target.createNewFile() }+                target.takeIf { it.exists() }+            }+            if (file == null) { cancel(); return@launch }+            val uri = uriForFile(file)+            if (uri == null) { cancel(); return@launch }+            finishWithResult(listOf(uri), write = true, persistable = privileged)+        }+    }++    private fun uniqueChild(dir: File, name: String): File {+        var candidate = File(dir, name)+        if (!candidate.exists()) return candidate+        val dot = name.lastIndexOf('.')+        val base = if (dot > 0) name.substring(0, dot) else name+        val ext = if (dot > 0) name.substring(dot) else ""+        var n = 1+        while (candidate.exists()) { candidate = File(dir, "$base ($n)$ext"); n++ }+        return candidate+    }++    private fun finishWithResult(uris: List<Uri>, write: Boolean, persistable: Boolean) {+        val result = Intent()+        var flags = Intent.FLAG_GRANT_READ_URI_PERMISSION+        if (write) flags = flags or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+        if (persistable) flags = flags or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION+        if (uris.size == 1) {+            result.data = uris[0]+        } else {+            val clip = ClipData.newUri(contentResolver, "files", uris[0])+            for (i in 1 until uris.size) clip.addItem(ClipData.Item(uris[i]))+            result.clipData = clip+        }+        result.addFlags(flags)+        setResult(RESULT_OK, result)+        finish()+    }++    private fun cancel() {+        setResult(RESULT_CANCELED)+        finish()+    }+}
files/src/main/java/com/vayunmathur/files/saf/StorageUris.kt
diff --git a/files/src/main/java/com/vayunmathur/files/saf/StorageUris.kt b/files/src/main/java/com/vayunmathur/files/saf/StorageUris.ktnew file mode 100644index 0000000000..852f505c4d--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/saf/StorageUris.kt@@ -0,0 +1,82 @@+package com.vayunmathur.files.saf++import android.content.Context+import android.net.Uri+import android.os.storage.StorageManager+import android.provider.DocumentsContract+import android.webkit.MimeTypeMap+import androidx.core.content.FileProvider+import java.io.File++/**+ * Maps between real [File]s and the platform ExternalStorageProvider's document IDs, so the SAF+ * picker can hand back the same provider-backed `content://com.android.externalstorage.documents`+ * URIs that DocumentsUI returns. Those URIs are queryable via [DocumentsContract] and support+ * persistable permission grants — unlike `file://` or one-shot FileProvider URIs.+ *+ * A document ID is `"<volumeId>:<relativePath>"`, e.g. `primary:Download/report.pdf`. The primary+ * shared volume uses the id `primary`; other volumes use their StorageVolume UUID (the same id+ * ExternalStorageProvider itself uses).+ */+object StorageUris {+    const val EXTERNAL_STORAGE_AUTHORITY = "com.android.externalstorage.documents"++    /** Document id (e.g. `primary:Pictures/a.jpg`) for [file], or null if it isn't on a known volume. */+    fun documentIdFor(context: Context, file: File): String? {+        val sm = context.getSystemService(StorageManager::class.java) ?: return null+        val path = file.absolutePath+        // Longest matching volume root wins (handles nested mount points deterministically).+        val best = sm.storageVolumes+            .mapNotNull { vol -> vol.directory?.let { it to vol } }+            .filter { (dir, _) -> path == dir.absolutePath || path.startsWith(dir.absolutePath + "/") }+            .maxByOrNull { (dir, _) -> dir.absolutePath.length }+            ?: return null+        val (dir, vol) = best+        val volumeId = if (vol.isPrimary) "primary" else (vol.uuid ?: return null)+        val relative = path.removePrefix(dir.absolutePath).trimStart('/')+        return "$volumeId:$relative"+    }++    /** Provider-backed single-document URI for [file], or null if it isn't on a known volume. */+    fun documentUriFor(context: Context, file: File): Uri? =+        documentIdFor(context, file)?.let {+            DocumentsContract.buildDocumentUri(EXTERNAL_STORAGE_AUTHORITY, it)+        }++    /** Provider-backed tree URI for directory [dir], or null if it isn't on a known volume. */+    fun treeUriFor(context: Context, dir: File): Uri? =+        documentIdFor(context, dir)?.let {+            DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_AUTHORITY, it)+        }++    /**+     * Fallback URI for a plain (non-privileged) `GET_CONTENT` response, where we can't grant a+     * provider URI. Returns a FileProvider URI the caller can read via a one-shot grant.+     */+    fun fileProviderUriFor(context: Context, file: File): Uri =+        FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)++    fun mimeTypeOf(file: File): String =+        MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())+            ?: "application/octet-stream"++    /**+     * Whether [file] satisfies the caller's requested MIME constraints. [filters] come from the+     * request's `type` plus `EXTRA_MIME_TYPES`; an empty list means "any".+     */+    fun matchesMime(file: File, filters: List<String>): Boolean {+        if (filters.isEmpty() || filters.any { it == "*/*" }) return true+        val mime = mimeTypeOf(file)+        return filters.any { filter -> mimeMatches(filter, mime) }+    }++    private fun mimeMatches(filter: String, mime: String): Boolean {+        if (filter == mime) return true+        val slash = filter.indexOf('/')+        if (slash < 0) return false+        val fType = filter.substring(0, slash)+        val fSub = filter.substring(slash + 1)+        if (fType != "*" && !mime.startsWith("$fType/")) return false+        return fSub == "*" || mime.endsWith("/$fSub")+    }+}
files/src/main/res/values/strings.xml
diff --git a/files/src/main/res/values/strings.xml b/files/src/main/res/values/strings.xmlindex a10bec151a..db4a612d62 100644--- a/files/src/main/res/values/strings.xml+++ b/files/src/main/res/values/strings.xml@@ -131,4 +131,18 @@     <string name="items_count"><xliff:g id="count" example="12">%1$d</xliff:g> item(s)</string>     <!-- Close a dialog -->     <string name="close">Close</string>++    <!-- SAF document picker (shown only when Files is the system documents UI) -->+    <!-- Title when the caller is opening/selecting existing files -->+    <string name="saf_title_open">Select a file</string>+    <!-- Title when the caller is creating/saving a new file -->+    <string name="saf_title_create">Save file</string>+    <!-- Title when the caller is picking a folder (grants access to the whole tree) -->+    <string name="saf_title_tree">Select a folder</string>+    <!-- Button confirming the current folder as the picked tree -->+    <string name="saf_use_this_folder">Use this folder</string>+    <!-- Button saving a newly created document -->+    <string name="saf_save">Save</string>+    <!-- Button confirming a multi-file selection. %1$d = number selected -->+    <string name="saf_select_count">Select (<xliff:g id="count" example="3">%1$d</xliff:g>)</string> </resources>