Modern Apps git

← Modern-Apps.git

code: migrate file backend from SAF to java.io.File with all-files access

Commit
da41b699dc3a1821f61fd0fb17d6c33cfc6b01b9
Author
Vayun Mathur <[email protected]>
When
2026-08-06 22:13 UTC (4 months ago)
Parents
095fff8

Diff

code/src/main/AndroidManifest.xml
diff --git a/code/src/main/AndroidManifest.xml b/code/src/main/AndroidManifest.xmlindex c3324837a6..4d2cc89178 100644--- a/code/src/main/AndroidManifest.xml+++ b/code/src/main/AndroidManifest.xml@@ -1,6 +1,10 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> +    <!-- Real filesystem access so git and the terminal can operate on the opened project.+         Acceptable for F-Droid / sideload; would be risky on Google Play. -->+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />+     <application         android:allowBackup="true"         android:dataExtractionRules="@xml/data_extraction_rules"
code/src/main/java/com/vayunmathur/code/MainActivity.kt
diff --git a/code/src/main/java/com/vayunmathur/code/MainActivity.kt b/code/src/main/java/com/vayunmathur/code/MainActivity.ktindex 3deac3477b..b150bf4ddf 100644--- a/code/src/main/java/com/vayunmathur/code/MainActivity.kt+++ b/code/src/main/java/com/vayunmathur/code/MainActivity.kt@@ -1,18 +1,31 @@ package com.vayunmathur.code  import android.content.Intent+import android.net.Uri import android.os.Bundle+import android.os.Environment+import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels+import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import com.vayunmathur.code.ui.EditorPage+import com.vayunmathur.code.ui.FolderBrowserPage import com.vayunmathur.code.ui.SearchPage import com.vayunmathur.code.ui.SettingsPage import com.vayunmathur.code.util.EditorPrefs import com.vayunmathur.code.util.EditorViewModel import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconFolderOpen+import com.vayunmathur.library.ui.PermissionWall+import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.openSettingsIfRequested@@ -22,9 +35,13 @@ import kotlinx.serialization.Serializable class MainActivity : ComponentActivity() {     private val viewModel: EditorViewModel by viewModels() +    /** All-files-access grant state. Re-checked in [onResume] since it is toggled in Settings. */+    private var hasStoragePermission by mutableStateOf(false)+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()+        hasStoragePermission = Environment.isExternalStorageManager()         handleIntent(intent)         setContent {             val darkTheme = when (viewModel.themeMode) {@@ -33,16 +50,37 @@ class MainActivity : ComponentActivity() {                 else -> null             }             DynamicTheme(darkTheme = darkTheme) {-                Navigation(viewModel)+                if (hasStoragePermission) {+                    Navigation(viewModel)+                } else {+                    StoragePermissionGate(onRequest = ::launchManageAllFilesAccess)+                }             }         }     } +    override fun onResume() {+        super.onResume()+        hasStoragePermission = Environment.isExternalStorageManager()+    }+     override fun onNewIntent(intent: Intent) {         super.onNewIntent(intent)         handleIntent(intent)     } +    /** Deep-links to the per-app "All files access" system screen; falls back to the list screen. */+    private fun launchManageAllFilesAccess() {+        val perApp = Intent(+            Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,+            Uri.fromParts("package", packageName, null),+        )+        val ok = runCatching { startActivity(perApp) }.isSuccess+        if (!ok) {+            runCatching { startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)) }+        }+    }+     /** VIEW/EDIT opens from other apps carry the file in [Intent.getData]; open it in a tab. */     private fun handleIntent(intent: Intent?) {         intent ?: return@@ -52,6 +90,21 @@ class MainActivity : ComponentActivity() {     } } +/** Shown until the user grants All-files access, which the whole editor depends on. */+@Composable+private fun StoragePermissionGate(onRequest: () -> Unit) {+    Scaffold { padding ->+        PermissionWall(+            title = stringResource(R.string.storage_permission_title),+            rationale = stringResource(R.string.storage_permission_rationale),+            actionLabel = stringResource(R.string.grant_access),+            onRequest = onRequest,+            icon = { IconFolderOpen() },+            modifier = Modifier.padding(padding),+        )+    }+}+ @Serializable sealed interface Route : NavKey {     @Serializable@@ -62,6 +115,9 @@ sealed interface Route : NavKey {      @Serializable     data object Search : Route++    @Serializable+    data object FolderBrowser : Route }  @Composable@@ -75,9 +131,11 @@ fun Navigation(viewModel: EditorViewModel) {                 viewModel,                 onOpenSettings = { backStack.add(Route.Settings) },                 onOpenSearch = { backStack.add(Route.Search) },+                onOpenFolder = { backStack.add(Route.FolderBrowser) },             )         }         entry<Route.Settings> { SettingsPage(viewModel, backStack) }         entry<Route.Search> { SearchPage(viewModel, backStack) }+        entry<Route.FolderBrowser> { FolderBrowserPage(viewModel, backStack) }     } }
code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.ktindex 4629e5e7c6..0032e42302 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -74,11 +74,8 @@ fun EditorPage(     viewModel: EditorViewModel,     onOpenSettings: () -> Unit = {},     onOpenSearch: () -> Unit = {},+    onOpenFolder: () -> Unit = {}, ) {-    val folderLauncher = rememberLauncherForActivityResult(-        ActivityResultContracts.OpenDocumentTree()-    ) { uri -> uri?.let(viewModel::openFolder) }-     val fileLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.OpenDocument()     ) { uri -> uri?.let(viewModel::openExternal) }@@ -86,7 +83,7 @@ fun EditorPage(     EditorScreen(         state = viewModel.uiState,         actions = viewModel,-        onOpenFolder = { folderLauncher.launch(null) },+        onOpenFolder = onOpenFolder,         onOpenFile = { fileLauncher.launch(arrayOf("*/*")) },         onOpenSettings = onOpenSettings,         onOpenSearch = onOpenSearch,@@ -95,8 +92,8 @@ fun EditorPage(  /**  * Top-level editor scaffold: a navigation drawer holding the [FileTreePane], a top bar to- * open it, then a tab strip, toolbar, optional find bar and the [CodeEditor] itself. The- * folder/file pickers use the Storage Access Framework so no storage permissions are needed.+ * open it, then a tab strip, toolbar, optional find bar and the [CodeEditor] itself. Opening a+ * folder navigates to the in-app folder browser; single files still use the system file picker.  *  * No dependency on the ViewModel, so it can be rendered from a `@Preview` — see  * `src/screenshotTest`, which is where the store listing images come from.
code/src/main/java/com/vayunmathur/code/ui/FolderBrowserPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/FolderBrowserPage.kt b/code/src/main/java/com/vayunmathur/code/ui/FolderBrowserPage.ktnew file mode 100644index 0000000000..d876281755--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/FolderBrowserPage.kt@@ -0,0 +1,108 @@+package com.vayunmathur.code.ui++import android.os.Environment+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+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.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.code.R+import com.vayunmathur.code.Route+import com.vayunmathur.code.util.FileFiles+import com.vayunmathur.code.util.EditorViewModel+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconChevronRight+import com.vayunmathur.library.ui.IconFolder+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.io.File++/**+ * In-app folder picker. Android has no "pick a folder → get a path" system API once we work over+ * real [File] paths, so this drills through directories from external storage and lets the user+ * open the current one as the project root. Replaces the old SAF `OpenDocumentTree` launcher.+ */+@Composable+fun FolderBrowserPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) {+    val storageRoot = remember { Environment.getExternalStorageDirectory() }+    var currentDir by remember { mutableStateOf(storageRoot) }+    var dirs by remember { mutableStateOf<List<File>>(emptyList()) }++    LaunchedEffect(currentDir) {+        dirs = withContext(Dispatchers.IO) {+            FileFiles.listChildren(currentDir).filter { it.isDirectory }.map { it.file }+        }+    }++    AppScaffold(title = stringResource(R.string.open_folder), backStack = backStack) { padding ->+        Column(Modifier.padding(padding).fillMaxSize()) {+            Text(+                text = currentDir.absolutePath,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+            )+            Button(+                onClick = {+                    viewModel.openFolder(currentDir)+                    backStack.pop()+                },+                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+            ) { Text(stringResource(R.string.open_this_folder)) }+            Spacer(Modifier.width(8.dp))+            HorizontalDivider()++            LazyColumn(Modifier.fillMaxSize()) {+                val parent = currentDir.parentFile+                if (parent != null && currentDir.absolutePath != storageRoot.absolutePath) {+                    item(key = "..") {+                        FolderRow(name = "..", onClick = { currentDir = parent })+                    }+                }+                items(dirs, key = { it.absolutePath }) { dir ->+                    FolderRow(name = dir.name, onClick = { currentDir = dir })+                }+            }+        }+    }+}++@Composable+private fun FolderRow(name: String, onClick: () -> Unit) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .clickable(onClick = onClick)+            .padding(horizontal = 16.dp, vertical = 12.dp),+        verticalAlignment = Alignment.CenterVertically,+        horizontalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        IconFolder(Modifier.width(24.dp))+        Text(text = name, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)+        IconChevronRight(Modifier.width(20.dp))+    }+}
code/src/main/java/com/vayunmathur/code/ui/SearchPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/SearchPage.kt b/code/src/main/java/com/vayunmathur/code/ui/SearchPage.ktindex 17dc7043e7..f8ea129a60 100644--- a/code/src/main/java/com/vayunmathur/code/ui/SearchPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/SearchPage.kt@@ -92,7 +92,7 @@ fun SearchPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) {             }              val groups = remember(state.searchResults) {-                state.searchResults.groupBy { it.name to it.uri }+                state.searchResults.groupBy { it.name to it.path }             }             LazyColumn(Modifier.fillMaxSize()) {                 groups.forEach { (key, results) ->
code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.ktindex 9c74e4a5fd..56f9d06edc 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -2,7 +2,6 @@ package com.vayunmathur.code.util  import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue-import android.net.Uri import com.vayunmathur.code.syntax.Language  /**@@ -13,7 +12,7 @@ import com.vayunmathur.code.syntax.Language  * generated from. It lives in `util` rather than `ui` so the dependency runs one way:  * `ui` depends on `util`, and the ViewModel implements [CodeActions].  *- * Note that the URIs, undo stacks and SAF plumbing behind these values stay in `util`:+ * Note that the file paths, undo stacks and IO plumbing behind these values stay in `util`:  * nothing the UI draws needs them, and a preview could not supply them.  */ @@ -35,9 +34,9 @@ data class TreeRowUiState(     val expanded: Boolean = false, ) -/** One hit from a project-wide search: the file, the 1-based line and a preview of that line. */+/** One hit from a project-wide search: the file path, the 1-based line and a preview of that line. */ data class SearchResult(-    val uri: Uri,+    val path: String,     val name: String,     val line: Int,     val preview: String,
code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.ktindex 0bb1c0c23d..01ba4d3f70 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -15,14 +15,14 @@ private val Context.editorDataStore: DataStore<Preferences> by preferencesDataSt  /**  * Persists the small amount of state that should survive relaunches: the last opened folder- * tree (so the file browser reopens where it was) and the editor preferences (soft-wrap, font+ * path (so the file browser reopens where it was) and the editor preferences (soft-wrap, font  * size, tab width, theme mode and the smart-input toggles).  */ class EditorPrefs(context: Context) {      private val appContext = context.applicationContext -    val folderUri: Flow<String?> = appContext.editorDataStore.data.map { it[FOLDER_URI_KEY] }+    val folderPath: Flow<String?> = appContext.editorDataStore.data.map { it[FOLDER_PATH_KEY] }     val softWrap: Flow<Boolean> = appContext.editorDataStore.data.map { it[SOFT_WRAP_KEY] ?: false }     val fontSize: Flow<Int> = appContext.editorDataStore.data.map { it[FONT_SIZE_KEY] ?: DEFAULT_FONT_SIZE }     val tabWidth: Flow<Int> = appContext.editorDataStore.data.map { it[TAB_WIDTH_KEY] ?: DEFAULT_TAB_WIDTH }@@ -31,12 +31,12 @@ class EditorPrefs(context: Context) {     val autoCloseBrackets: Flow<Boolean> =         appContext.editorDataStore.data.map { it[AUTO_CLOSE_KEY] ?: true } -    suspend fun setFolderUri(uri: String) {-        appContext.editorDataStore.edit { it[FOLDER_URI_KEY] = uri }+    suspend fun setFolderPath(path: String) {+        appContext.editorDataStore.edit { it[FOLDER_PATH_KEY] = path }     } -    suspend fun clearFolderUri() {-        appContext.editorDataStore.edit { it.remove(FOLDER_URI_KEY) }+    suspend fun clearFolderPath() {+        appContext.editorDataStore.edit { it.remove(FOLDER_PATH_KEY) }     }      suspend fun setSoftWrap(enabled: Boolean) {@@ -70,7 +70,7 @@ class EditorPrefs(context: Context) {         const val THEME_LIGHT = "light"         const val THEME_DARK = "dark" -        private val FOLDER_URI_KEY = stringPreferencesKey("folder_uri")+        private val FOLDER_PATH_KEY = stringPreferencesKey("folder_path")         private val SOFT_WRAP_KEY = booleanPreferencesKey("soft_wrap")         private val FONT_SIZE_KEY = intPreferencesKey("font_size")         private val TAB_WIDTH_KEY = intPreferencesKey("tab_width")
code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.ktindex 7f3b81ce4d..3f4e48d755 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -3,14 +3,12 @@ package com.vayunmathur.code.util import android.app.Application import android.content.Intent import android.net.Uri-import android.provider.DocumentsContract import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue-import androidx.core.net.toUri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.code.syntax.Language@@ -20,10 +18,11 @@ import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import java.io.File import kotlin.coroutines.coroutineContext  /** One expandable row in the file-tree pane; the tree is stored as a flat, ordered list. */-class TreeNode(val entry: DocEntry, val depth: Int) {+class TreeNode(val entry: FileEntry, val depth: Int) {     var expanded by mutableStateOf(false)     var loading by mutableStateOf(false) }@@ -32,14 +31,20 @@ class TreeNode(val entry: DocEntry, val depth: Int) {  * One open file. Editor content lives in [value]; [savedText] is the last persisted text so  * [isDirty] can drive the unsaved-dot. Undo/redo are plain deques (not observed directly);  * [canUndo]/[canRedo] mirror their emptiness as state so the toolbar buttons stay reactive.+ *+ * Most tabs are backed by a real [file]. Files opened through a VIEW/EDIT intent from another+ * app arrive as a `content://` [externalUri] instead and are [readOnly] (no `save` target).  */ class OpenTab(-    uri: Uri,+    file: File?,+    externalUri: Uri? = null,+    val readOnly: Boolean = false,     initialName: String,     initialText: String,     language: Language, ) {-    var uri by mutableStateOf(uri)+    var file by mutableStateOf(file)+    var externalUri by mutableStateOf(externalUri)     var name by mutableStateOf(initialName)     var language by mutableStateOf(language)     var value by mutableStateOf(TextFieldValue(initialText))@@ -52,6 +57,9 @@ class OpenTab(     private val undoStack = ArrayDeque<TextFieldValue>()     private val redoStack = ArrayDeque<TextFieldValue>() +    /** Stable identity used to dedup tabs: the file path, or the external URI string. */+    val key: String get() = file?.absolutePath ?: externalUri.toString()+     val isDirty: Boolean get() = value.text != savedText      fun pushUndo(previous: TextFieldValue) {@@ -91,6 +99,9 @@ class OpenTab(  * It implements [CodeActions] and projects itself into a [CodeUiState] so the screens can be  * rendered without it; reading [uiState] inside a composable subscribes to the same  * `mutableStateOf`/`mutableStateListOf` members the screens used to read directly.+ *+ * The file backend is real [File] paths (the app holds `MANAGE_EXTERNAL_STORAGE`), so folder,+ * tree and file operations all go through [FileFiles].  */ class EditorViewModel(application: Application) : AndroidViewModel(application), CodeActions { @@ -98,11 +109,10 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     private val prefs = EditorPrefs(context)      // ---- File tree -----    var treeUri by mutableStateOf<Uri?>(null)+    var rootDir by mutableStateOf<File?>(null)         private set     var rootName by mutableStateOf<String?>(null)         private set-    private var rootDocumentId: String? = null     val nodes = mutableStateListOf<TreeNode>()      // ---- Tabs ----@@ -114,16 +124,21 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     // ---- Preferences ----     var softWrap by mutableStateOf(false)         private set-    var fontSize by mutableStateOf(EditorPrefs.DEFAULT_FONT_SIZE)-        private set-    var tabWidth by mutableStateOf(EditorPrefs.DEFAULT_TAB_WIDTH)-        private set-    var themeMode by mutableStateOf(EditorPrefs.THEME_SYSTEM)-        private set-    var autoIndent by mutableStateOf(true)-        private set-    var autoCloseBrackets by mutableStateOf(true)-        private set++    // These five are read as `fontSize`/`tabWidth`/... but written through the CodeActions+    // `setFontSize`/`setTabWidth`/... methods. Backing them by a private MutableState (rather than+    // a `var ... private set`) avoids a JVM signature clash between the generated property setter+    // and the same-named interface method.+    private val _fontSize = mutableStateOf(EditorPrefs.DEFAULT_FONT_SIZE)+    val fontSize: Int get() = _fontSize.value+    private val _tabWidth = mutableStateOf(EditorPrefs.DEFAULT_TAB_WIDTH)+    val tabWidth: Int get() = _tabWidth.value+    private val _themeMode = mutableStateOf(EditorPrefs.THEME_SYSTEM)+    val themeMode: String get() = _themeMode.value+    private val _autoIndent = mutableStateOf(true)+    val autoIndent: Boolean get() = _autoIndent.value+    private val _autoCloseBrackets = mutableStateOf(true)+    val autoCloseBrackets: Boolean get() = _autoCloseBrackets.value      // ---- Project search ----     val searchResults = mutableStateListOf<SearchResult>()@@ -147,7 +162,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             currentIndex = currentIndex,             softWrap = softWrap,             rootName = rootName,-            folderOpen = treeUri != null,+            folderOpen = rootDir != null,             nodes = nodes.map {                 TreeRowUiState(                     name = it.entry.name,@@ -166,45 +181,44 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),      init {         viewModelScope.launch { softWrap = prefs.softWrap.first() }-        viewModelScope.launch { fontSize = prefs.fontSize.first() }-        viewModelScope.launch { tabWidth = prefs.tabWidth.first() }-        viewModelScope.launch { themeMode = prefs.themeMode.first() }-        viewModelScope.launch { autoIndent = prefs.autoIndent.first() }-        viewModelScope.launch { autoCloseBrackets = prefs.autoCloseBrackets.first() }+        viewModelScope.launch { _fontSize.value = prefs.fontSize.first() }+        viewModelScope.launch { _tabWidth.value = prefs.tabWidth.first() }+        viewModelScope.launch { _themeMode.value = prefs.themeMode.first() }+        viewModelScope.launch { _autoIndent.value = prefs.autoIndent.first() }+        viewModelScope.launch { _autoCloseBrackets.value = prefs.autoCloseBrackets.first() }         viewModelScope.launch {-            val stored = prefs.folderUri.first() ?: return@launch-            val uri = stored.toUri()-            val loaded = runCatching { loadFolder(uri) }.isSuccess-            if (!loaded) prefs.clearFolderUri()+            val stored = prefs.folderPath.first() ?: return@launch+            val dir = File(stored)+            if (dir.isDirectory) {+                runCatching { loadFolder(dir) }.onFailure { prefs.clearFolderPath() }+            } else {+                prefs.clearFolderPath()+            }         }     }      // ---- Folder handling ---- -    /** Persists read/write access to a freshly picked tree and loads its top level. */-    fun openFolder(uri: Uri) {-        val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION-        runCatching { context.contentResolver.takePersistableUriPermission(uri, flags) }+    /** Opens [dir] as the project root and loads its top level, persisting it for relaunch. */+    fun openFolder(dir: File) {         viewModelScope.launch {-            prefs.setFolderUri(uri.toString())-            loadFolder(uri)+            prefs.setFolderPath(dir.absolutePath)+            runCatching { loadFolder(dir) }         }     }      fun closeFolder() {-        treeUri = null+        rootDir = null         rootName = null-        rootDocumentId = null         nodes.clear()-        viewModelScope.launch { prefs.clearFolderUri() }+        viewModelScope.launch { prefs.clearFolderPath() }     } -    private suspend fun loadFolder(uri: Uri) {-        val root = withContext(Dispatchers.IO) { SafFiles.rootEntry(context, uri) }-        val children = withContext(Dispatchers.IO) { SafFiles.listChildren(context, uri, root.documentId) }-        treeUri = uri-        rootName = root.name-        rootDocumentId = root.documentId+    private suspend fun loadFolder(dir: File) {+        require(dir.isDirectory) { "Not a directory: $dir" }+        val children = withContext(Dispatchers.IO) { FileFiles.listChildren(dir) }+        rootDir = dir+        rootName = dir.name         nodes.clear()         nodes.addAll(children.map { TreeNode(it, depth = 0) })     }@@ -213,10 +227,9 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     override fun toggleNode(index: Int) {         val node = nodes.getOrNull(index) ?: return         if (!node.entry.isDirectory) {-            openFile(node.entry.uri, node.entry.name)+            openFile(node.entry.file)             return         }-        val tree = treeUri ?: return          if (node.expanded) {             node.expanded = false@@ -225,9 +238,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             node.expanded = true             node.loading = true             viewModelScope.launch {-                val children = withContext(Dispatchers.IO) {-                    SafFiles.listChildren(context, tree, node.entry.documentId)-                }+                val children = withContext(Dispatchers.IO) { FileFiles.listChildren(node.entry.file) }                 node.loading = false                 // The row may have been collapsed again while loading; only insert if still open.                 val at = nodes.indexOf(node)@@ -250,13 +261,12 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),      /**      * Re-lists the children of a folder and rebuilds that subtree in [nodes]. Expansion state-     * and already-loaded descendant rows of immediate child folders are preserved by document id.+     * and already-loaded descendant rows of immediate child folders are preserved by path.      * [parentIndex] null refreshes the tree root.      */     private suspend fun refreshChildren(parentIndex: Int?) {-        val tree = treeUri ?: return-        val parentDocId = if (parentIndex == null) rootDocumentId ?: return-        else nodes.getOrNull(parentIndex)?.entry?.documentId ?: return+        val parentFile = if (parentIndex == null) rootDir ?: return+        else nodes.getOrNull(parentIndex)?.entry?.file ?: return         val parentDepth = if (parentIndex == null) -1 else nodes[parentIndex].depth         val childDepth = parentDepth + 1 @@ -264,7 +274,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         var blockEnd = blockStart         while (blockEnd < nodes.size && nodes[blockEnd].depth > parentDepth) blockEnd++ -        // Preserve existing immediate children (and their loaded subtrees) by document id.+        // Preserve existing immediate children (and their loaded subtrees) by path.         val preservedNode = HashMap<String, TreeNode>()         val preservedSubtree = HashMap<String, List<TreeNode>>()         var i = blockStart@@ -273,22 +283,24 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             if (child.depth == childDepth) {                 var j = i + 1                 while (j < blockEnd && nodes[j].depth > childDepth) j++-                preservedNode[child.entry.documentId] = child-                preservedSubtree[child.entry.documentId] = nodes.subList(i + 1, j).toList()+                val key = child.entry.file.absolutePath+                preservedNode[key] = child+                preservedSubtree[key] = nodes.subList(i + 1, j).toList()                 i = j             } else {                 i++             }         } -        val entries = withContext(Dispatchers.IO) { SafFiles.listChildren(context, tree, parentDocId) }+        val entries = withContext(Dispatchers.IO) { FileFiles.listChildren(parentFile) }          val rebuilt = ArrayList<TreeNode>()         for (entry in entries) {-            val existing = preservedNode[entry.documentId]+            val key = entry.file.absolutePath+            val existing = preservedNode[key]             if (existing != null) {                 rebuilt.add(existing)-                rebuilt.addAll(preservedSubtree[entry.documentId].orEmpty())+                rebuilt.addAll(preservedSubtree[key].orEmpty())             } else {                 rebuilt.add(TreeNode(entry, childDepth))             }@@ -298,32 +310,24 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         nodes.addAll(blockStart, rebuilt)     } -    /** Resolves the document id of a create target: the tree root, or a directory row. */-    private fun parentDocId(parentIndex: Int?): String? =-        if (parentIndex == null) rootDocumentId else nodes.getOrNull(parentIndex)?.entry?.documentId+    /** Resolves the create target directory: the tree root, or a directory row. */+    private fun parentFileFor(parentIndex: Int?): File? =+        if (parentIndex == null) rootDir else nodes.getOrNull(parentIndex)?.entry?.file      override fun createFile(parentIndex: Int?, name: String) {-        val tree = treeUri ?: return-        val parentDoc = parentDocId(parentIndex) ?: return+        val parent = parentFileFor(parentIndex) ?: return         viewModelScope.launch {-            val uri = withContext(Dispatchers.IO) {-                SafFiles.createDocument(context, tree, parentDoc, name, SafFiles.mimeForFileName(name))-            } ?: return@launch+            val file = withContext(Dispatchers.IO) { FileFiles.createFile(parent, name) } ?: return@launch             nodes.getOrNull(parentIndex ?: -1)?.expanded = true             refreshChildren(parentIndex)-            openFile(uri, name)+            openFile(file)         }     }      override fun createFolder(parentIndex: Int?, name: String) {-        val tree = treeUri ?: return-        val parentDoc = parentDocId(parentIndex) ?: return+        val parent = parentFileFor(parentIndex) ?: return         viewModelScope.launch {-            withContext(Dispatchers.IO) {-                SafFiles.createDocument(-                    context, tree, parentDoc, name, DocumentsContract.Document.MIME_TYPE_DIR,-                )-            } ?: return@launch+            withContext(Dispatchers.IO) { FileFiles.createDirectory(parent, name) } ?: return@launch             nodes.getOrNull(parentIndex ?: -1)?.expanded = true             refreshChildren(parentIndex)         }@@ -331,81 +335,107 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),      override fun renameNode(index: Int, newName: String) {         val node = nodes.getOrNull(index) ?: return-        val oldUri = node.entry.uri+        val oldFile = node.entry.file         viewModelScope.launch {-            val newUri = withContext(Dispatchers.IO) {-                SafFiles.renameDocument(context, oldUri, newName)-            } ?: return@launch-            val newDocId = runCatching { DocumentsContract.getDocumentId(newUri) }-                .getOrDefault(node.entry.documentId)+            val newFile = withContext(Dispatchers.IO) { FileFiles.rename(oldFile, newName) } ?: return@launch             val at = nodes.indexOf(node)             if (at >= 0) {-                // A renamed directory's descendant ids may shift; drop them so a re-expand re-lists.+                // A renamed directory's descendant paths shift; drop them so a re-expand re-lists.                 if (node.entry.isDirectory) removeDescendants(at)-                val newEntry = node.entry.copy(documentId = newDocId, name = newName, uri = newUri)-                nodes[at] = TreeNode(newEntry, node.depth)+                nodes[at] = TreeNode(FileEntry(newFile, newName, node.entry.isDirectory), node.depth)             }-            tabs.firstOrNull { it.uri == oldUri }?.let { tab ->-                tab.uri = newUri-                tab.name = newName-                tab.language = Language.fromFileName(newName)+            // Repoint open tabs backed by the renamed file (or living under a renamed directory).+            val oldPath = oldFile.absolutePath+            val newPath = newFile.absolutePath+            for (tab in tabs) {+                val p = tab.file?.absolutePath ?: continue+                if (p == oldPath) {+                    tab.file = newFile+                    tab.name = newName+                    tab.language = Language.fromFileName(newName)+                } else if (p.startsWith(oldPath + File.separator)) {+                    tab.file = File(newPath + p.substring(oldPath.length))+                }             }         }     }      override fun deleteNode(index: Int) {         val node = nodes.getOrNull(index) ?: return-        val uri = node.entry.uri+        val file = node.entry.file         viewModelScope.launch {-            val ok = withContext(Dispatchers.IO) { SafFiles.deleteDocument(context, uri) }+            val ok = withContext(Dispatchers.IO) { FileFiles.delete(file) }             if (!ok) return@launch             val at = nodes.indexOf(node)             if (at >= 0) {                 removeDescendants(at)                 nodes.removeAt(at)             }-            closeTabsUnder(uri)+            closeTabsUnder(file)         }     } -    /** Closes any open tab whose file is [uri] or lives beneath it (for a deleted directory). */-    private fun closeTabsUnder(uri: Uri) {-        val target = uri.toString()+    /** Closes any open tab whose file is [file] or lives beneath it (for a deleted directory). */+    private fun closeTabsUnder(file: File) {+        val target = file.absolutePath+        val prefix = target + File.separator         for (i in tabs.indices.reversed()) {-            val tabUri = tabs[i].uri.toString()-            if (tabUri == target || tabUri.startsWith("$target%2F") || tabUri.startsWith("$target/")) {-                closeTab(i)-            }+            val p = tabs[i].file?.absolutePath ?: continue+            if (p == target || p.startsWith(prefix)) closeTab(i)         }     }      // ---- Tab handling ---- -    /** Opens [uri] in a tab (focusing it if already open), reading its text off the main thread. */-    fun openFile(uri: Uri, name: String? = null) {-        val existing = tabs.indexOfFirst { it.uri == uri }+    /** Opens [file] in a tab (focusing it if already open), reading its text off the main thread. */+    fun openFile(file: File) {+        val key = file.absolutePath+        val existing = tabs.indexOfFirst { it.key == key }         if (existing >= 0) {             currentIndex = existing             return         }         viewModelScope.launch {-            val displayName = name-                ?: withContext(Dispatchers.IO) { SafFiles.queryDisplayName(context, uri) }-                ?: "untitled"             val text = withContext(Dispatchers.IO) {-                runCatching { SafFiles.readText(context, uri) }.getOrDefault("")+                runCatching { FileFiles.readText(file) }.getOrDefault("")             }-            tabs.add(OpenTab(uri, displayName, text, Language.fromFileName(displayName)))+            tabs.add(OpenTab(file = file, initialName = file.name, initialText = text, language = Language.fromFileName(file.name)))             currentIndex = tabs.lastIndex         }     }      /** Handles a VIEW/EDIT intent that carries a single file URI. */     fun openExternal(uri: Uri) {+        if (uri.scheme == "file") {+            uri.path?.let { openFile(File(it)) }+            return+        }         runCatching {             context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)         }-        openFile(uri)+        val key = uri.toString()+        val existing = tabs.indexOfFirst { it.key == key }+        if (existing >= 0) {+            currentIndex = existing+            return+        }+        viewModelScope.launch {+            val displayName = withContext(Dispatchers.IO) { FileFiles.queryDisplayName(context, uri) } ?: "untitled"+            val text = withContext(Dispatchers.IO) {+                runCatching { FileFiles.readTextFromUri(context, uri) }.getOrDefault("")+            }+            tabs.add(+                OpenTab(+                    file = null,+                    externalUri = uri,+                    readOnly = true,+                    initialName = displayName,+                    initialText = text,+                    language = Language.fromFileName(displayName),+                )+            )+            currentIndex = tabs.lastIndex+        }     }      override fun selectTab(index: Int) {@@ -457,10 +487,11 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),      override fun save() {         val tab = currentTab ?: return+        val file = tab.file ?: return // external read-only tabs have no save target         val textToSave = tab.value.text         viewModelScope.launch {             val ok = withContext(Dispatchers.IO) {-                runCatching { SafFiles.writeText(context, tab.uri, textToSave) }.isSuccess+                runCatching { FileFiles.writeText(file, textToSave) }.isSuccess             }             if (ok) tab.savedText = textToSave         }@@ -482,27 +513,27 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     }      override fun setFontSize(size: Int) {-        fontSize = size+        _fontSize.value = size         viewModelScope.launch { prefs.setFontSize(size) }     }      override fun setTabWidth(width: Int) {-        tabWidth = width+        _tabWidth.value = width         viewModelScope.launch { prefs.setTabWidth(width) }     }      override fun setThemeMode(mode: String) {-        themeMode = mode+        _themeMode.value = mode         viewModelScope.launch { prefs.setThemeMode(mode) }     }      override fun setAutoIndent(enabled: Boolean) {-        autoIndent = enabled+        _autoIndent.value = enabled         viewModelScope.launch { prefs.setAutoIndent(enabled) }     }      override fun setAutoCloseBrackets(enabled: Boolean) {-        autoCloseBrackets = enabled+        _autoCloseBrackets.value = enabled         viewModelScope.launch { prefs.setAutoCloseBrackets(enabled) }     } @@ -557,8 +588,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     // ---- Project search ----      override fun searchProject(query: String, caseSensitive: Boolean, useRegex: Boolean) {-        val tree = treeUri ?: return-        val rootId = rootDocumentId ?: return+        val root = rootDir ?: return         searchJob?.cancel()         if (query.isBlank()) {             searchResults.clear()@@ -570,26 +600,24 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         searchJob = viewModelScope.launch {             val collected = withContext(Dispatchers.IO) {                 val out = ArrayList<SearchResult>()-                val stack = ArrayDeque<String>()-                stack.addLast(rootId)+                val stack = ArrayDeque<File>()+                stack.addLast(root)                 while (stack.isNotEmpty() && out.size < MAX_SEARCH_RESULTS) {                     coroutineContext.ensureActive()-                    val dirId = stack.removeLast()-                    val children = runCatching {-                        SafFiles.listChildren(context, tree, dirId)-                    }.getOrDefault(emptyList())+                    val dir = stack.removeLast()+                    val children = runCatching { FileFiles.listChildren(dir) }.getOrDefault(emptyList())                     for (child in children) {                         if (out.size >= MAX_SEARCH_RESULTS) break                         if (child.isDirectory) {-                            if (child.name !in SKIP_DIRS) stack.addLast(child.documentId)+                            if (child.name !in SKIP_DIRS) stack.addLast(child.file)                             continue                         }                         if (Language.fromFileName(child.name) == Language.PLAINTEXT) continue-                        val text = runCatching { SafFiles.readText(context, child.uri) }.getOrNull() ?: continue-                        if (text.length > MAX_SEARCH_FILE_SIZE) continue+                        if (child.file.length() > MAX_SEARCH_FILE_SIZE) continue+                        val text = runCatching { FileFiles.readText(child.file) }.getOrNull() ?: continue                         val matches = findLineMatches(text, query, caseSensitive, useRegex, MAX_MATCHES_PER_FILE)                         for (m in matches) {-                            out.add(SearchResult(child.uri, child.name, m.line, m.preview))+                            out.add(SearchResult(child.file.absolutePath, child.name, m.line, m.preview))                             if (out.size >= MAX_SEARCH_RESULTS) break                         }                     }@@ -603,17 +631,18 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     }      override fun openSearchResult(result: SearchResult) {-        val existing = tabs.indexOfFirst { it.uri == result.uri }+        val existing = tabs.indexOfFirst { it.key == result.path }         if (existing >= 0) {             currentIndex = existing             goToLine(result.line)             return         }+        val file = File(result.path)         viewModelScope.launch {             val text = withContext(Dispatchers.IO) {-                runCatching { SafFiles.readText(context, result.uri) }.getOrDefault("")+                runCatching { FileFiles.readText(file) }.getOrDefault("")             }-            tabs.add(OpenTab(result.uri, result.name, text, Language.fromFileName(result.name)))+            tabs.add(OpenTab(file = file, initialName = result.name, initialText = text, language = Language.fromFileName(result.name)))             currentIndex = tabs.lastIndex             goToLine(result.line)         }
code/src/main/java/com/vayunmathur/code/util/FileFiles.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/FileFiles.kt b/code/src/main/java/com/vayunmathur/code/util/FileFiles.ktnew file mode 100644index 0000000000..6a5b650210--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/FileFiles.kt@@ -0,0 +1,105 @@+package com.vayunmathur.code.util++import android.content.Context+import android.net.Uri+import java.io.File++/**+ * A single entry (file or directory) on the real filesystem.+ *+ * Replaces the SAF `DocEntry`: with `MANAGE_EXTERNAL_STORAGE` the editor works over real+ * [File] paths, so identity is just the [file] itself — no document ids to track.+ */+data class FileEntry(+    val file: File,+    val name: String,+    val isDirectory: Boolean,+)++/**+ * Thin wrappers over [java.io.File].+ *+ * All calls here hit the disk and may block, so callers run them off the main thread. Nothing+ * is cached: the file tree is rebuilt lazily as folders expand, which keeps large trees cheap+ * and always in sync with the on-disk state. This is the single file backend — the app holds+ * All-files access, so `content://` only appears for VIEW/EDIT intents from other apps+ * ([readTextFromUri]).+ */+object FileFiles {++    /** Wraps a [File] into a browsable [FileEntry]. */+    fun entryFor(file: File): FileEntry = FileEntry(file, file.name, file.isDirectory)++    /**+     * Lists the direct children of [dir], sorted with directories first and then+     * case-insensitively by name (VS Code's ordering, matching the old SAF backend).+     */+    fun listChildren(dir: File): List<FileEntry> {+        val children = dir.listFiles() ?: return emptyList()+        return children+            .map { FileEntry(it, it.name, it.isDirectory) }+            .sortedWith(compareByDescending<FileEntry> { it.isDirectory }.thenBy { it.name.lowercase() })+    }++    /** Reads the full UTF-8 text of a file. */+    fun readText(file: File): String = file.readText(Charsets.UTF_8)++    /** Overwrites a file with [text] (truncating any previous contents). */+    fun writeText(file: File, text: String) = file.writeText(text, Charsets.UTF_8)++    /**+     * Creates a new empty file (and any missing parent directories) under [parent]. Returns the+     * new [File], or null if it already exists or creation failed.+     */+    fun createFile(parent: File, name: String): File? = runCatching {+        val target = File(parent, name)+        target.parentFile?.mkdirs()+        if (target.createNewFile()) target else null+    }.getOrNull()++    /** Creates a new directory under [parent]. Returns it, or null on failure. */+    fun createDirectory(parent: File, name: String): File? {+        val target = File(parent, name)+        val ok = runCatching { target.mkdirs() }.getOrDefault(false) || target.isDirectory+        return if (ok) target else null+    }++    /** Renames a file/dir within its parent. Returns the new [File], or null on failure. */+    fun rename(file: File, newName: String): File? {+        val target = File(file.parentFile, newName)+        return if (runCatching { file.renameTo(target) }.getOrDefault(false)) target else null+    }++    /** Deletes a file, or a directory and everything under it. Returns true on success. */+    fun delete(file: File): Boolean = runCatching { file.deleteRecursively() }.getOrDefault(false)++    /** Reads text from an external `content://`/`file://` URI, for VIEW/EDIT intents. */+    fun readTextFromUri(context: Context, uri: Uri): String {+        context.contentResolver.openInputStream(uri).use { input ->+            requireNotNull(input) { "Unable to open $uri for reading" }+            return input.bufferedReader().use { it.readText() }+        }+    }++    /** Best-effort display name for an external URI. */+    fun queryDisplayName(context: Context, uri: Uri): String? = runCatching {+        val projection = arrayOf(android.provider.OpenableColumns.DISPLAY_NAME)+        context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->+            if (cursor.moveToFirst()) cursor.getString(0) else null+        }+    }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')++    /** A best-effort MIME type for a file name; defaults to plain text. */+    fun mimeForFileName(name: String): String {+        val ext = name.substringAfterLast('.', "").lowercase()+        return when (ext) {+            "json" -> "application/json"+            "xml" -> "text/xml"+            "html", "htm" -> "text/html"+            "css" -> "text/css"+            "js", "mjs", "cjs" -> "text/javascript"+            "md", "markdown" -> "text/markdown"+            else -> "text/plain"+        }+    }+}
code/src/main/java/com/vayunmathur/code/util/SafFiles.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/SafFiles.kt b/code/src/main/java/com/vayunmathur/code/util/SafFiles.ktdeleted file mode 100644index 1af890c000..0000000000--- a/code/src/main/java/com/vayunmathur/code/util/SafFiles.kt+++ /dev/null@@ -1,137 +0,0 @@-package com.vayunmathur.code.util--import android.content.Context-import android.database.Cursor-import android.net.Uri-import android.provider.DocumentsContract--/**- * A single entry (file or directory) discovered through the Storage Access Framework.- *- * We keep the [documentId] around because child enumeration and document-URI- * construction are both keyed off document ids rather than the URIs themselves.- */-data class DocEntry(-    val documentId: String,-    val name: String,-    val uri: Uri,-    val isDirectory: Boolean,-)--/**- * Thin wrappers over [DocumentsContract] + [android.content.ContentResolver].- *- * All calls here touch the content resolver and may block, so callers run them off- * the main thread. Nothing is cached: the file tree is rebuilt lazily as folders- * expand, which keeps large trees cheap and always in sync with the on-disk state.- */-object SafFiles {--    /** Resolves the root document of a persisted tree URI into a browsable [DocEntry]. */-    fun rootEntry(context: Context, treeUri: Uri): DocEntry {-        val rootId = DocumentsContract.getTreeDocumentId(treeUri)-        val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, rootId)-        val name = queryDisplayName(context, docUri) ?: treeUri.lastPathSegment.orEmpty()-        return DocEntry(rootId, name, docUri, isDirectory = true)-    }--    /**-     * Lists the direct children of [parentDocumentId] inside [treeUri], sorted with-     * directories first and then case-insensitively by name (VS Code's ordering).-     */-    fun listChildren(context: Context, treeUri: Uri, parentDocumentId: String): List<DocEntry> {-        val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocumentId)-        val result = ArrayList<DocEntry>()-        val projection = arrayOf(-            DocumentsContract.Document.COLUMN_DOCUMENT_ID,-            DocumentsContract.Document.COLUMN_DISPLAY_NAME,-            DocumentsContract.Document.COLUMN_MIME_TYPE,-        )-        context.contentResolver.query(childrenUri, projection, null, null, null)?.use { cursor: Cursor ->-            val idCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)-            val nameCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)-            val mimeCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)-            while (cursor.moveToNext()) {-                val docId = cursor.getString(idCol)-                val name = cursor.getString(nameCol) ?: continue-                val mime = cursor.getString(mimeCol)-                val isDir = mime == DocumentsContract.Document.MIME_TYPE_DIR-                val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId)-                result.add(DocEntry(docId, name, docUri, isDir))-            }-        }-        return result.sortedWith(-            compareByDescending<DocEntry> { it.isDirectory }.thenBy { it.name.lowercase() }-        )-    }--    /** Reads a document's display name; used for single-file and external-intent opens. */-    fun queryDisplayName(context: Context, uri: Uri): String? {-        val projection = arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME)-        return runCatching {-            context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->-                if (cursor.moveToFirst()) cursor.getString(0) else null-            }-        }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')-    }--    /** Reads the full UTF-8 text of a document. */-    fun readText(context: Context, uri: Uri): String {-        context.contentResolver.openInputStream(uri).use { input ->-            requireNotNull(input) { "Unable to open $uri for reading" }-            return input.bufferedReader().use { it.readText() }-        }-    }--    /**-     * Overwrites a document with [text]. The `"wt"` mode truncates first so shrinking-     * a file doesn't leave stale trailing bytes behind.-     */-    fun writeText(context: Context, uri: Uri, text: String) {-        context.contentResolver.openOutputStream(uri, "wt").use { output ->-            requireNotNull(output) { "Unable to open $uri for writing" }-            output.write(text.toByteArray(Charsets.UTF_8))-            output.flush()-        }-    }--    /**-     * Creates a new document (file or folder) under [parentDocumentId]. Pass-     * [DocumentsContract.Document.MIME_TYPE_DIR] as [mimeType] for a folder, or a file MIME-     * (see [mimeForFileName]) for a file. Returns the new document's URI, or null on failure.-     */-    fun createDocument(-        context: Context,-        treeUri: Uri,-        parentDocumentId: String,-        displayName: String,-        mimeType: String,-    ): Uri? {-        val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, parentDocumentId)-        return runCatching {-            DocumentsContract.createDocument(context.contentResolver, parentUri, mimeType, displayName)-        }.getOrNull()-    }--    /** Renames a document, returning the (possibly changed) URI, or null on failure. */-    fun renameDocument(context: Context, uri: Uri, newName: String): Uri? =-        runCatching { DocumentsContract.renameDocument(context.contentResolver, uri, newName) }.getOrNull()--    /** Deletes a document. Returns true on success. */-    fun deleteDocument(context: Context, uri: Uri): Boolean =-        runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }.getOrDefault(false)--    /** A best-effort MIME type for a new file name; defaults to plain text. */-    fun mimeForFileName(name: String): String {-        val ext = name.substringAfterLast('.', "").lowercase()-        return when (ext) {-            "json" -> "application/json"-            "xml" -> "text/xml"-            "html", "htm" -> "text/html"-            "css" -> "text/css"-            "js", "mjs", "cjs" -> "text/javascript"-            "md", "markdown" -> "text/markdown"-            else -> "text/plain"-        }-    }-}
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlindex eb2d770704..402232848a 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -48,4 +48,8 @@     <string name="searching">Searching\u2026</string>     <string name="no_results">No results</string>     <string name="line_number">Line %1$d</string>+    <string name="storage_permission_title">Storage access needed</string>+    <string name="storage_permission_rationale">Code needs all-files access to open your projects, run git and use the terminal on real file paths.</string>+    <string name="grant_access">Grant access</string>+    <string name="open_this_folder">Open this folder</string> </resources>