Modern Apps git

← Modern-Apps.git

files: one back stack entry per folder so Back goes up one level

Commit
264d1e8c503d955a87afeb5adb17d2ca7c68b14c
Author
vayun-mathur <[email protected]>
When
2026-08-29 01:36 UTC (3 months ago)
Parents
3fa5593

Diff

files/src/main/java/com/vayunmathur/files/Navigation.kt
diff --git a/files/src/main/java/com/vayunmathur/files/Navigation.kt b/files/src/main/java/com/vayunmathur/files/Navigation.ktindex e96022340d..0326da4f95 100644--- a/files/src/main/java/com/vayunmathur/files/Navigation.kt+++ b/files/src/main/java/com/vayunmathur/files/Navigation.kt@@ -1,10 +1,64 @@ package com.vayunmathur.files  import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember import com.vayunmathur.files.platform.FilesViewModel-import com.vayunmathur.files.ui.HomeDirectoryPage+import com.vayunmathur.files.ui.DirectoryPage+import com.vayunmathur.files.ui.FilesShell+import com.vayunmathur.files.ui.HomeScreenBinder+import com.vayunmathur.files.ui.filesNavActions+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import java.io.File +/**+ * One view model holds one location, so each destination claims it when it becomes the current one -+ * hence the `isCurrent` guard repeated below. It is needed on the way forward *and* on the way back,+ * because popping to a folder already on the stack has to reload it; and it stops the outgoing entry+ * reloading its own folder mid-transition, fighting the incoming one for the same state.+ */ @Composable fun Navigation(viewModel: FilesViewModel) {-    HomeDirectoryPage(viewModel)+    val backStack = rememberNavBackStack<Route>(Route.Home)+    val actions = remember(viewModel, backStack) { filesNavActions(viewModel, backStack) }++    // An archive becomes a destination only once the view model has confirmed it opens, so a corrupt+    // zip reports an error where the user is instead of navigating into a listing that cannot load.+    LaunchedEffect(viewModel, backStack) {+        viewModel.zipOpened.collect { backStack.add(Route.Zip(it.absolutePath)) }+    }++    FilesShell(viewModel, actions) { openDrawer ->+        MainNavigation(backStack) {+            entry<Route.Home> {+                val isCurrent = backStack.last() == Route.Home+                LaunchedEffect(isCurrent) { if (isCurrent) viewModel.goHome() }+                HomeScreenBinder(viewModel, actions, openDrawer)+            }+            entry<Route.Directory> { route ->+                val isCurrent = backStack.last() == route+                LaunchedEffect(route, isCurrent) {+                    if (isCurrent) viewModel.navigateTo(File(route.path))+                }+                DirectoryPage(viewModel, actions, isCurrent, openDrawer)+            }+            // A category listing spans every folder, so it has nowhere to go "up" to: it always+            // sits directly on Home rather than on the folder it was opened from.+            entry<Route.Category> { route ->+                val isCurrent = backStack.last() == route+                LaunchedEffect(route, isCurrent) {+                    if (isCurrent) viewModel.openCategory(route.category)+                }+                DirectoryPage(viewModel, actions, isCurrent, openDrawer)+            }+            entry<Route.Zip> { route ->+                val isCurrent = backStack.last() == route+                LaunchedEffect(route, isCurrent) {+                    if (isCurrent) viewModel.showZip(File(route.zipPath), route.internalPath)+                }+                DirectoryPage(viewModel, actions, isCurrent, openDrawer)+            }+        }+    } }
files/src/main/java/com/vayunmathur/files/Route.kt
diff --git a/files/src/main/java/com/vayunmathur/files/Route.kt b/files/src/main/java/com/vayunmathur/files/Route.ktindex be6b62c436..ecc7becdd2 100644--- a/files/src/main/java/com/vayunmathur/files/Route.kt+++ b/files/src/main/java/com/vayunmathur/files/Route.kt@@ -1,12 +1,38 @@ package com.vayunmathur.files +import com.vayunmathur.files.platform.FileCategory import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/**+ * Where the browser is, as navigation rather than as view-model state.+ *+ * Depth is the point. A folder three levels down is three entries, not one entry holding a long+ * path, because that is what makes Back go up exactly one level and lets the predictive-back+ * preview show the folder the gesture will actually land on. The previous single [Home]/`Browser`+ * pair could not express depth at all, so directory traversal lived in `FilesViewModel.handleBack`+ * and the system gesture had nothing to animate.+ */ @Serializable sealed interface Route : NavKey {     @Serializable     data object Home : Route++    /** A folder on the real filesystem. One entry per level. */+    @Serializable+    data class Directory(val path: String) : Route++    /**+     * A flat, cross-directory listing - every image on the device, say - so it has no parent folder+     * to go up to and always sits directly on top of [Home].+     */+    @Serializable+    data class Category(val category: FileCategory) : Route++    /**+     * Inside an archive. [internalPath] is empty at the archive root and gains one entry per folder+     * within it, so Back walks out of the archive the same way it walks up a directory.+     */     @Serializable-    data object Browser : Route+    data class Zip(val zipPath: String, val internalPath: String = "") : Route }
files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.kt b/files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.ktindex 75b09a5b97..1b6744f680 100644--- a/files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.kt@@ -84,6 +84,13 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),     private val _zipPath = MutableStateFlow<File?>(null)     val zipPath: StateFlow<File?> = _zipPath.asStateFlow() +    /**+     * Emitted once an archive has been confirmed readable, so that navigation happens only for a zip+     * that actually opens. Validation is IO, so it cannot be done by the caller before navigating.+     */+    private val _zipOpened = MutableSharedFlow<File>(extraBufferCapacity = 4)+    val zipOpened: SharedFlow<File> = _zipOpened.asSharedFlow()+     private val _zipInternalPath = MutableStateFlow("")     val zipInternalPath: StateFlow<String> = _zipInternalPath.asStateFlow() @@ -254,9 +261,6 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),     }      // ---- Home screen: storage, recents, bookmarks, categories -----    private val _atHome = MutableStateFlow(true)-    val atHome: StateFlow<Boolean> = _atHome.asStateFlow()-     private val _categoryTitle = MutableStateFlow<String?>(null)     val categoryTitle: StateFlow<String?> = _categoryTitle.asStateFlow() @@ -278,7 +282,6 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),     }      override fun goHome() {-        _atHome.value = true         _categoryTitle.value = null         _zipPath.value = null         _zipInternalPath.value = ""@@ -303,7 +306,6 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),             openBookmark(if (dl.isDirectory) dl else rootDirectory)             return         }-        _atHome.value = false         _zipPath.value = null         _categoryTitle.value = getApplication<Application>().getString(categoryLabel(category))         clearSelection()@@ -601,7 +603,6 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),             _zipPath.value = null             _zipInternalPath.value = ""         }-        _atHome.value = false         _categoryTitle.value = null         _currentDirectory.value = path         applyDirDefaults(path)@@ -634,34 +635,17 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),         restartObserver()     } +    /**+     * Back within a screen, not between screens.+     *+     * Directory, archive and category traversal used to live here, walking the location state by+     * hand. That is the navigation back stack's job now - one entry per level - and doing it in both+     * places meant the predictive-back preview showed one destination while this produced another.+     * What is left is the part that is genuinely not navigation: dismissing a selection.+     */     override fun handleBack(): Boolean {         if (_selectedPaths.value.isNotEmpty()) { clearSelection(); return true }-        if (_categoryTitle.value != null) { goHome(); return true }-        val z = _zipPath.value-        when {-            z != null -> {-                val internal = _zipInternalPath.value-                if (internal.isEmpty()) {-                    val parent = z.parentFile ?: rootDirectory-                    _zipPath.value = null-                    _currentDirectory.value = parent-                    restartObserver()-                } else {-                    val parentInternal = if (internal.contains("/")) internal.substringBeforeLast("/") else ""-                    _zipInternalPath.value = parentInternal-                }-                loadDirectory()-            }-            _currentDirectory.value.absolutePath != rootDirectory.absolutePath -> {-                _currentDirectory.value = _currentDirectory.value.parentFile ?: _currentDirectory.value-                applyDirDefaults(_currentDirectory.value)-                loadDirectory()-                restartObserver()-            }-            // At the storage root, Back returns to the home screen.-            else -> goHome()-        }-        return true+        return false     }      override fun rename(item: FileBrowserItem, newName: String) {@@ -716,23 +700,34 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),         }     } +    /**+     * Checks the archive can be read and, if so, reports it via [zipOpened] for the navigation layer+     * to act on. Deliberately changes no state: a corrupt archive should leave the user where they+     * are, with a message, rather than navigate into a listing that cannot load.+     */     override fun openZipFile(item: FileBrowserItem) {         val file = item.realFile ?: return         viewModelScope.launch(Dispatchers.IO) {             try {                 ZipFile(file).use { _ -> }-                _zipPath.value = file-                _zipInternalPath.value = ""-                _currentDirectory.value = File("/") // placeholder not used in zip mode-                clearSelection()-                loadDirectory()-                restartObserver()+                _zipOpened.emit(file)             } catch (e: Exception) {                 emit(getApplication<Application>().getString(R.string.could_not_open_zip, e.localizedMessage))             }         }     } +    /** Loads a location inside an archive. Called by the navigation layer for a `Route.Zip`. */+    fun showZip(zip: File, internalPath: String) {+        _categoryTitle.value = null+        _zipPath.value = zip+        _zipInternalPath.value = internalPath+        _currentDirectory.value = File("/") // placeholder not used in zip mode+        clearSelection()+        loadDirectory()+        restartObserver()+    }+     override fun archive(archiveName: String) {         if (isZipMode()) return         val ctx = getApplication<Application>()
files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.ktindex c53c33001b..066604986b 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt@@ -9,14 +9,26 @@ import androidx.compose.runtime.* import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources import com.vayunmathur.files.R+import com.vayunmathur.files.platform.FilesActions import com.vayunmathur.files.platform.FilesUiState import com.vayunmathur.files.platform.FilesViewModel import com.vayunmathur.library.ui.SnackbarHostState import java.io.File -/** Binds [FilesViewModel] to the stateless [DirectoryScreen]. */+/**+ * Binds [FilesViewModel] to the stateless [DirectoryScreen].+ *+ * [isCurrent] is false while this entry is animating away under a newer one. Every folder on the+ * back stack is a separate entry sharing one view model, so without it the outgoing screen would+ * repaint with the contents of the folder being opened just as it slides out of view.+ */ @Composable-fun DirectoryPage(viewModel: FilesViewModel, onOpenDrawer: () -> Unit = {}) {+fun DirectoryPage(+    viewModel: FilesViewModel,+    actions: FilesActions,+    isCurrent: Boolean,+    onOpenDrawer: () -> Unit = {},+) {     val context = LocalContext.current     val resources = LocalResources.current     val snackbarHostState = remember { SnackbarHostState() }@@ -83,28 +95,32 @@ fun DirectoryPage(viewModel: FilesViewModel, onOpenDrawer: () -> Unit = {}) {      val (directories, files) = entries +    val liveState = FilesUiState(+        rootDirectory = viewModel.rootDirectory,+        rootDisplayName = Build.MODEL,+        currentDirectory = currentDirectory,+        zipPath = zipPath,+        zipInternalPath = zipInternalPath,+        directories = directories,+        files = files,+        selectedPaths = selectedPaths,+        hasIncomingUris = incomingUris != null,+        sortBy = sortBy,+        sortAscending = sortAscending,+        viewMode = viewMode,+        searchQuery = searchQuery,+        isSearchActive = isSearchActive,+        clipboardCount = clipboard.size,+        clipboardIsCut = clipboardIsCut,+        showHidden = showHidden,+        categoryTitle = categoryTitle,+    )+    var lastShown by remember { mutableStateOf(liveState) }+    if (isCurrent) SideEffect { lastShown = liveState }+     DirectoryScreen(-        state = FilesUiState(-            rootDirectory = viewModel.rootDirectory,-            rootDisplayName = Build.MODEL,-            currentDirectory = currentDirectory,-            zipPath = zipPath,-            zipInternalPath = zipInternalPath,-            directories = directories,-            files = files,-            selectedPaths = selectedPaths,-            hasIncomingUris = incomingUris != null,-            sortBy = sortBy,-            sortAscending = sortAscending,-            viewMode = viewMode,-            searchQuery = searchQuery,-            isSearchActive = isSearchActive,-            clipboardCount = clipboard.size,-            clipboardIsCut = clipboardIsCut,-            showHidden = showHidden,-            categoryTitle = categoryTitle,-        ),-        actions = viewModel,+        state = if (isCurrent) liveState else lastShown,+        actions = actions,         snackbarHostState = snackbarHostState,         onPickUnzipDestination = { treeLauncher.launch(null) },         onOpenDrawer = onOpenDrawer,
files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.ktindex c320f0a7f3..fac6c5de64 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt@@ -252,13 +252,10 @@ fun DirectoryScreen(         crumbs     } -    BackHandler(-        state.currentDirectory.absolutePath != root.absolutePath ||-            state.selectedPaths.isNotEmpty() ||-            state.zipPath != null ||-            state.isSearchActive ||-            isCategory-    ) {+    // Only the parts of Back that are not navigation. Folder, archive and category depth are back+    // stack entries now, so everything else has to fall through to the navigation host - swallowing+    // it here would also swallow the predictive-back gesture and its preview.+    BackHandler(state.isSearchActive || state.selectedPaths.isNotEmpty()) {         itemBeingRenamed = null         if (state.isSearchActive) actions.setSearchActive(false) else actions.handleBack()     }
files/src/main/java/com/vayunmathur/files/ui/FilesNavActions.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/FilesNavActions.kt b/files/src/main/java/com/vayunmathur/files/ui/FilesNavActions.ktnew file mode 100644index 0000000000..adfebda2ea--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/ui/FilesNavActions.kt@@ -0,0 +1,100 @@+package com.vayunmathur.files.ui++import com.vayunmathur.files.Route+import com.vayunmathur.files.platform.FileBrowserItem+import com.vayunmathur.files.platform.FileCategory+import com.vayunmathur.files.platform.FilesActions+import com.vayunmathur.files.platform.FilesViewModel+import com.vayunmathur.library.util.NavBackStack+import java.io.File++/**+ * The [FilesActions] the screens are given: every action that changes *where* the user is becomes a+ * back stack operation, and everything else - copy, rename, sort, select - falls through to the+ * view model untouched.+ *+ * Delegation rather than a rewrite of the screens. `FilesActions` is one wide interface that the+ * view model implements, so `by viewModel` forwards the eighty-odd members that are not navigation+ * and leaves only the handful below to override. The screens keep calling `actions.navigateTo(...)`+ * and do not know the difference.+ */+internal fun filesNavActions(+    viewModel: FilesViewModel,+    backStack: NavBackStack<Route>,+): FilesActions = object : FilesActions by viewModel {++    private val root: File get() = viewModel.rootDirectory++    override fun goHome() = backStack.reset(Route.Home)++    override fun openInternalStorage() =+        backStack.reset(Route.Home, Route.Directory(root.absolutePath))++    /**+     * A bookmark can point anywhere, so the intermediate folders are synthesised rather than pushed+     * one at a time. Without them Back from a deep bookmark would jump straight to Home, skipping+     * every folder the breadcrumb bar is showing.+     */+    override fun openBookmark(path: File) = backStack.showDirectory(root, path)++    override fun openCategory(category: FileCategory) {+        // Downloads is a real folder rather than a media query, so it browses like one.+        if (category == FileCategory.DOWNLOADS) {+            val downloads = File(root, "Download")+            openBookmark(if (downloads.isDirectory) downloads else root)+        } else {+            backStack.reset(Route.Home, Route.Category(category))+        }+    }++    /**+     * Serves both descending into a child folder and tapping an ancestor in the breadcrumb bar. A+     * target already on the stack is popped back to, so jumping up does not stack a second copy of a+     * folder the user has already been through.+     */+    override fun navigateTo(path: File) {+        val target = Route.Directory(path.absolutePath)+        if (!backStack.popTo(target)) backStack.add(target)+    }++    override fun navigateIntoZipDir(dirName: String) {+        val current = backStack.backStack.lastOrNull() as? Route.Zip ?: return+        val child =+            if (current.internalPath.isEmpty()) dirName else "${current.internalPath}/$dirName"+        backStack.add(current.copy(internalPath = child))+    }++    override fun navigateToZipInternalPath(fullInternalPath: String) {+        val current = backStack.backStack.lastOrNull() as? Route.Zip ?: return+        val target = current.copy(internalPath = fullInternalPath)+        if (!backStack.popTo(target)) backStack.add(target)+    }++    /** Breadcrumb tap on the real-filesystem part of the trail while inside an archive. */+    override fun navigateToZipParentRealFolder(target: File) {+        val route = Route.Directory(target.absolutePath)+        if (!backStack.popTo(route)) backStack.showDirectory(root, target)+    }+}++/**+ * Pops until [target] is the current destination, reporting whether it was there to begin with.+ *+ * Returns false and changes nothing when the target is absent, so a caller can fall back to pushing+ * rather than unwinding the whole stack looking for something that was never on it.+ */+private fun NavBackStack<Route>.popTo(target: Route): Boolean {+    if (target !in backStack) return false+    while (backStack.size > 1 && backStack.last() != target) pop()+    return true+}++/** Replaces the stack with Home followed by one entry per folder from [root] down to [target]. */+private fun NavBackStack<Route>.showDirectory(root: File, target: File) {+    val chain = fileAncestors(target, root)+    if (chain.isEmpty()) {+        reset(Route.Home, Route.Directory(target.absolutePath))+    } else {+        reset(Route.Home, *chain.map { Route.Directory(it.absolutePath) }.toTypedArray())+    }+}
files/src/main/java/com/vayunmathur/files/ui/FilesShell.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/HomeDirectoryPage.kt b/files/src/main/java/com/vayunmathur/files/ui/FilesShell.ktsimilarity index 93%rename from files/src/main/java/com/vayunmathur/files/ui/HomeDirectoryPage.ktrename to files/src/main/java/com/vayunmathur/files/ui/FilesShell.ktindex 5baa751d7b..2944d00384 100644--- a/files/src/main/java/com/vayunmathur/files/ui/HomeDirectoryPage.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/FilesShell.kt@@ -29,8 +29,20 @@ import kotlinx.coroutines.launch import java.io.File  +/**+ * The chrome that is the same on every destination: the all-files permission gate, the notification+ * prompt, and the navigation drawer.+ *+ * Wraps the nav host rather than living inside it, so the drawer is not rebuilt on every navigation+ * and stays open across one. [content] is handed the callback that opens it, because the drawer state+ * belongs here but the buttons that open it are on the individual screens.+ */ @Composable-fun HomeDirectoryPage(viewModel: FilesViewModel) {+fun FilesShell(+    viewModel: FilesViewModel,+    actions: FilesActions,+    content: @Composable (openDrawer: () -> Unit) -> Unit,+) {     val context = LocalContext.current     val isFilesGranted by viewModel.isFilesGranted.collectAsState()     val hasPromptedNotifications by viewModel.hasPromptedNotifications.collectAsState()@@ -99,7 +111,6 @@ fun HomeDirectoryPage(viewModel: FilesViewModel) {                 }) { Text(stringResource(R.string.grant_all_files_access)) }         }     } else {-        val atHome by viewModel.atHome.collectAsState()         val bookmarks by viewModel.bookmarks.collectAsState()         val drawerState = rememberDrawerState(DrawerValue.Closed)         val scope = rememberCoroutineScope()@@ -109,17 +120,13 @@ fun HomeDirectoryPage(viewModel: FilesViewModel) {                 ModalDrawerSheet {                     FilesDrawer(                         bookmarks = bookmarks,-                        actions = viewModel,+                        actions = actions,                         closeDrawer = { scope.launch { drawerState.close() } },                     )                 }             },         ) {-            if (atHome) {-                HomeScreenBinder(viewModel) { scope.launch { drawerState.open() } }-            } else {-                DirectoryPage(viewModel) { scope.launch { drawerState.open() } }-            }+            content { scope.launch { drawerState.open() } }         }     } }
files/src/main/java/com/vayunmathur/files/ui/HomeScreenBinder.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/HomeScreenBinder.kt b/files/src/main/java/com/vayunmathur/files/ui/HomeScreenBinder.ktindex 73fc78e758..d871932acd 100644--- a/files/src/main/java/com/vayunmathur/files/ui/HomeScreenBinder.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/HomeScreenBinder.kt@@ -7,12 +7,17 @@ import androidx.compose.runtime.* import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources import com.vayunmathur.files.R+import com.vayunmathur.files.platform.FilesActions import com.vayunmathur.files.platform.FilesViewModel import com.vayunmathur.files.platform.HomeUiState import com.vayunmathur.library.ui.SnackbarHostState  @Composable-fun HomeScreenBinder(viewModel: FilesViewModel, onOpenDrawer: () -> Unit = {}) {+fun HomeScreenBinder(+    viewModel: FilesViewModel,+    actions: FilesActions,+    onOpenDrawer: () -> Unit = {},+) {     val context = LocalContext.current     val resources = LocalResources.current     val snackbarHostState = remember { SnackbarHostState() }@@ -51,7 +56,7 @@ fun HomeScreenBinder(viewModel: FilesViewModel, onOpenDrawer: () -> Unit = {}) {             recents = recents,             bookmarks = bookmarks,         ),-        actions = viewModel,+        actions = actions,         snackbarHostState = snackbarHostState,         onOpenDrawer = onOpenDrawer,     )