Modern Apps git

← Modern-Apps.git

files: full-featured manager — home, nav drawer, sort dir, grid, thumbnails, search, copy/paste, new/props/hidden/bookmarks

Commit
a39cad3150d82fa85799446312d4d5e47dcbf47b
Author
Vayun Mathur <[email protected]>
When
2026-08-04 18:29 UTC (4 months ago)
Parents
80488f9

Diff

files/build.gradle.kts
diff --git a/files/build.gradle.kts b/files/build.gradle.ktsindex c5be46f171..5a5d5b4147 100644--- a/files/build.gradle.kts+++ b/files/build.gradle.kts@@ -18,4 +18,6 @@ android { dependencies {     // Zip/unzip workers now use java.io.File + java.util.zip – no okio needed     implementation(libs.androidx.work.runtime.ktx)+    // Image thumbnails for image files in the browser (AsyncImage).+    implementation(project(":library:image")) }
files/src/main/java/com/vayunmathur/files/MainActivity.kt
diff --git a/files/src/main/java/com/vayunmathur/files/MainActivity.kt b/files/src/main/java/com/vayunmathur/files/MainActivity.ktindex b44ba71be3..7b31fa897c 100644--- a/files/src/main/java/com/vayunmathur/files/MainActivity.kt+++ b/files/src/main/java/com/vayunmathur/files/MainActivity.kt@@ -3,7 +3,6 @@ package com.vayunmathur.files import android.Manifest import android.content.ClipData import android.content.ClipDescription-import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri@@ -28,39 +27,59 @@ import androidx.compose.foundation.draganddrop.dragAndDropSource import androidx.compose.foundation.draganddrop.dragAndDropTarget import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource+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.Spacer 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.layout.size+import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items as gridItems import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.LinearProgressIndicator 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.SnackbarHost import com.vayunmathur.library.ui.SnackbarHostState+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.material3.DrawerValue+import androidx.compose.material3.ModalDrawerSheet+import androidx.compose.material3.ModalNavigationDrawer+import androidx.compose.material3.NavigationDrawerItem+import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment@@ -70,35 +89,72 @@ import androidx.compose.ui.draganddrop.DragAndDropTarget import androidx.compose.ui.draganddrop.DragAndDropTransferData import androidx.compose.ui.draganddrop.mimeTypes import androidx.compose.ui.draganddrop.toAndroidDragEvent+import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalResources-import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import android.text.format.Formatter import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.core.content.IntentCompat import com.vayunmathur.files.util.FileBrowserItem+import com.vayunmathur.files.util.FileCategory import com.vayunmathur.files.util.FilesActions import com.vayunmathur.files.util.FilesUiState import com.vayunmathur.files.util.FilesViewModel+import com.vayunmathur.files.util.HomeUiState+import com.vayunmathur.files.util.SortBy+import com.vayunmathur.files.util.StorageInfo+import com.vayunmathur.files.util.ViewMode+import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconArchive+import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconChevronRight import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconCode+import com.vayunmathur.library.ui.IconCopy import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconDescription+import com.vayunmathur.library.ui.IconDownload import com.vayunmathur.library.ui.IconEdit import com.vayunmathur.library.ui.IconFile import com.vayunmathur.library.ui.IconFolder+import com.vayunmathur.library.ui.IconGrid+import com.vayunmathur.library.ui.IconHome+import com.vayunmathur.library.ui.IconImage+import com.vayunmathur.library.ui.IconInfo+import com.vayunmathur.library.ui.IconLibraryMusic+import com.vayunmathur.library.ui.IconList+import com.vayunmathur.library.ui.IconMenu+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconNewFile+import com.vayunmathur.library.ui.IconNewFolder+import com.vayunmathur.library.ui.IconPackage import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.IconSearch+import com.vayunmathur.library.ui.IconShare+import com.vayunmathur.library.ui.IconStar import com.vayunmathur.library.ui.IconUnarchive+import com.vayunmathur.library.ui.IconVideoCamera+import com.vayunmathur.library.ui.IconVisibilityOff+import com.vayunmathur.library.ui.IconVisible+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import java.io.File+import java.text.DateFormat+import java.util.Date  class MainActivity : ComponentActivity() {     private val viewModel: FilesViewModel by viewModels()@@ -203,7 +259,99 @@ fun HomeDirectoryPage(viewModel: FilesViewModel) {                 }) { Text(stringResource(R.string.grant_all_files_access)) }         }     } else {-        DirectoryPage(viewModel)+        val atHome by viewModel.atHome.collectAsState()+        val bookmarks by viewModel.bookmarks.collectAsState()+        val drawerState = rememberDrawerState(DrawerValue.Closed)+        val scope = rememberCoroutineScope()+        ModalNavigationDrawer(+            drawerState = drawerState,+            drawerContent = {+                ModalDrawerSheet {+                    FilesDrawer(+                        bookmarks = bookmarks,+                        actions = viewModel,+                        closeDrawer = { scope.launch { drawerState.close() } },+                    )+                }+            },+        ) {+            if (atHome) {+                HomeScreenBinder(viewModel) { scope.launch { drawerState.open() } }+            } else {+                DirectoryPage(viewModel) { scope.launch { drawerState.open() } }+            }+        }+    }+}++/** The slide-out navigation drawer: jump to any page without going Home first. */+@Composable+private fun FilesDrawer(+    bookmarks: List<FileBrowserItem>,+    actions: FilesActions,+    closeDrawer: () -> Unit,+) {+    fun go(action: () -> Unit) { action(); closeDrawer() }+    Column(Modifier.padding(12.dp)) {+        Text(+            stringResource(R.string.app_name),+            style = MaterialTheme.typography.titleLarge,+            modifier = Modifier.padding(16.dp),+        )+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.home)) },+            icon = { IconHome() },+            selected = false,+            onClick = { go { actions.goHome() } },+        )+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.internal_storage)) },+            icon = { IconFolder() },+            selected = false,+            onClick = { go { actions.openInternalStorage() } },+        )+        SectionHeader(stringResource(R.string.categories))+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.cat_images)) },+            icon = { IconImage(tint = COLOR_IMAGE) },+            selected = false,+            onClick = { go { actions.openCategory(FileCategory.IMAGES) } },+        )+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.cat_videos)) },+            icon = { IconVideoCamera(tint = COLOR_VIDEO) },+            selected = false,+            onClick = { go { actions.openCategory(FileCategory.VIDEOS) } },+        )+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.cat_audio)) },+            icon = { IconLibraryMusic(tint = COLOR_AUDIO) },+            selected = false,+            onClick = { go { actions.openCategory(FileCategory.AUDIO) } },+        )+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.cat_documents)) },+            icon = { IconDescription(tint = COLOR_DOC) },+            selected = false,+            onClick = { go { actions.openCategory(FileCategory.DOCUMENTS) } },+        )+        NavigationDrawerItem(+            label = { Text(stringResource(R.string.cat_downloads)) },+            icon = { IconDownload(tint = COLOR_APK) },+            selected = false,+            onClick = { go { actions.openCategory(FileCategory.DOWNLOADS) } },+        )+        if (bookmarks.isNotEmpty()) {+            SectionHeader(stringResource(R.string.bookmarks))+            bookmarks.forEach { bm ->+                NavigationDrawerItem(+                    label = { Text(bm.name) },+                    icon = { IconStar() },+                    selected = false,+                    onClick = { go { bm.realFile?.let { actions.openBookmark(it) } } },+                )+            }+        }     } } @@ -213,10 +361,6 @@ private fun fileAncestors(from: File?, upTo: File?): List<File> = buildList {         add(0, p)         if (upTo != null && p.absolutePath == upTo.absolutePath) break         p = p.parentFile-        // Prevent infinite if upTo not in chain: stop when p becomes child of upTo? We'll just keep going up-        // but avoid adding files above upTo by breaking if upTo != null and p != null and !from!!.absolutePath.startsWith(p.absolutePath) etc not needed-        // Simpler: if upTo != null and p != null and !p.absolutePath.startsWith(upTo.absolutePath) and upTo.absolutePath != p.absolutePath? then break after adding upTo?-        // For our external storage use case it's fine.     } } @@ -250,7 +394,7 @@ fun dropTarget(  /** Binds [FilesViewModel] to the stateless [DirectoryScreen]. */ @Composable-fun DirectoryPage(viewModel: FilesViewModel) {+fun DirectoryPage(viewModel: FilesViewModel, onOpenDrawer: () -> Unit = {}) {     val context = LocalContext.current     val resources = LocalResources.current     val snackbarHostState = remember { SnackbarHostState() }@@ -261,6 +405,15 @@ fun DirectoryPage(viewModel: FilesViewModel) {     val selectedPaths by viewModel.selectedPaths.collectAsState()     val entries by viewModel.entries.collectAsState()     val incomingUris by viewModel.incomingUris.collectAsState()+    val sortBy by viewModel.sortBy.collectAsState()+    val sortAscending by viewModel.sortAscending.collectAsState()+    val viewMode by viewModel.viewMode.collectAsState()+    val searchQuery by viewModel.searchQuery.collectAsState()+    val isSearchActive by viewModel.isSearchActive.collectAsState()+    val clipboard by viewModel.clipboard.collectAsState()+    val clipboardIsCut by viewModel.clipboardIsCut.collectAsState()+    val showHidden by viewModel.showHidden.collectAsState()+    val categoryTitle by viewModel.categoryTitle.collectAsState()      LaunchedEffect(snackbarHostState) {         viewModel.snackbarMessages.collect { message ->@@ -309,13 +462,69 @@ fun DirectoryPage(viewModel: FilesViewModel) {             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,         snackbarHostState = snackbarHostState,         onPickUnzipDestination = { treeLauncher.launch(null) },+        onOpenDrawer = onOpenDrawer,     ) } +// ---- File type / thumbnail helpers ----++private val IMAGE_EXTS = setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "heic", "heif", "avif")+private val VIDEO_EXTS = setOf("mp4", "mkv", "webm", "mov", "avi", "3gp", "m4v", "flv", "ts")+private val AUDIO_EXTS = setOf("mp3", "wav", "flac", "ogg", "m4a", "aac", "opus", "mid", "amr")+private val DOC_EXTS = setOf("pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "md", "rtf", "csv", "odt")+private val ARCHIVE_EXTS = setOf("zip", "rar", "7z", "tar", "gz", "bz2", "xz")+private val CODE_EXTS = setOf("kt", "java", "c", "cpp", "h", "py", "js", "ts", "html", "css", "json", "xml", "sh", "rs", "go")++private val COLOR_IMAGE = Color(0xFF4CAF50)+private val COLOR_VIDEO = Color(0xFF9C27B0)+private val COLOR_AUDIO = Color(0xFFFF9800)+private val COLOR_DOC = Color(0xFF2196F3)+private val COLOR_ARCHIVE = Color(0xFFFFC107)+private val COLOR_APK = Color(0xFF009688)+private val COLOR_CODE = Color(0xFF607D8B)++/** Leading visual for a browser item: an image thumbnail, or a type-colored icon. */+@Composable+private fun FileLeading(item: FileBrowserItem, isSelected: Boolean, sizeDp: Dp) {+    val ext = item.name.substringAfterLast('.', "").lowercase()+    if (!item.isDirectory && item.realFile != null && ext in IMAGE_EXTS) {+        AsyncImage(+            model = item.realFile,+            contentDescription = null,+            modifier = Modifier+                .size(sizeDp)+                .clip(RoundedCornerShape(6.dp)),+            contentScale = ContentScale.Crop,+        )+        return+    }+    val folderTint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline+    when {+        item.isDirectory -> IconFolder(tint = folderTint)+        ext in VIDEO_EXTS -> IconVideoCamera(tint = COLOR_VIDEO)+        ext in AUDIO_EXTS -> IconLibraryMusic(tint = COLOR_AUDIO)+        ext in DOC_EXTS -> IconDescription(tint = COLOR_DOC)+        ext in ARCHIVE_EXTS -> IconArchive(tint = COLOR_ARCHIVE)+        ext == "apk" -> IconPackage(tint = COLOR_APK)+        ext in CODE_EXTS -> IconCode(tint = COLOR_CODE)+        ext in IMAGE_EXTS -> IconImage(tint = COLOR_IMAGE)+        else -> IconFile(tint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline)+    }+}+ /**  * The directory browser, with 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.@@ -329,16 +538,27 @@ fun DirectoryScreen(     snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },     /** Opens the system folder picker for "unzip here"; needs an Activity. */     onPickUnzipDestination: () -> Unit = {},+    /** Opens the navigation drawer. */+    onOpenDrawer: () -> Unit = {}, ) {     val isReadOnly = state.zipPath != null+    val isCategory = state.categoryTitle != null+    // A category view lists files gathered from across storage, so structural edits+    // (new/paste/move/rename/archive) that target "here" don't apply.+    val canModifyHere = !isReadOnly && !isCategory     val root = state.rootDirectory -    var pathBeingRenamed by remember { mutableStateOf<FileBrowserItem?>(null) }+    var itemBeingRenamed by remember { mutableStateOf<FileBrowserItem?>(null) }+    var itemForProperties by remember { mutableStateOf<FileBrowserItem?>(null) }     var showArchiveDialog by remember { mutableStateOf(false) }     var archiveName by remember { mutableStateOf("archive.zip") }+    var showOverflow by remember { mutableStateOf(false) }+    var showSelectionOverflow by remember { mutableStateOf(false) }+    var showNewFolderDialog by remember { mutableStateOf(false) }+    var showNewFileDialog by remember { mutableStateOf(false) }      LaunchedEffect(state.selectedPaths) {-        if (state.selectedPaths.isEmpty()) pathBeingRenamed = null+        if (state.selectedPaths.isEmpty()) itemBeingRenamed = null     }      if (showArchiveDialog) {@@ -367,10 +587,59 @@ fun DirectoryScreen(             })     } -    val zipToUnzip = remember(state.selectedPaths) {-        state.selectedPaths.singleOrNull()?.takeIf {-            !it.isDirectory && it.realFile != null && it.name.endsWith(".zip", ignoreCase = true)-        }+    itemBeingRenamed?.let { renaming ->+        var newName by remember(renaming.key) { mutableStateOf(renaming.name) }+        AlertDialog(+            onDismissRequest = { itemBeingRenamed = null },+            title = { Text(stringResource(R.string.rename)) },+            text = {+                TextField(+                    value = newName,+                    onValueChange = { newName = it },+                    label = { Text(stringResource(R.string.new_name_label)) },+                    singleLine = true,+                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+                    keyboardActions = KeyboardActions(onDone = {+                        actions.rename(renaming, newName)+                        itemBeingRenamed = null+                    })+                )+            },+            confirmButton = {+                TextButton(onClick = {+                    actions.rename(renaming, newName)+                    itemBeingRenamed = null+                }) { Text(stringResource(R.string.rename)) }+            },+            dismissButton = {+                TextButton(onClick = { itemBeingRenamed = null }) {+                    Text(stringResource(UiR.string.cancel))+                }+            })+    }++    if (showNewFolderDialog) {+        NameDialog(+            title = stringResource(R.string.new_folder),+            label = stringResource(R.string.folder_name_label),+            initial = "",+            confirmLabel = stringResource(R.string.create),+            onConfirm = { actions.createFolder(it); showNewFolderDialog = false },+            onDismiss = { showNewFolderDialog = false },+        )+    }+    if (showNewFileDialog) {+        NameDialog(+            title = stringResource(R.string.new_file),+            label = stringResource(R.string.file_name_label),+            initial = "untitled.txt",+            confirmLabel = stringResource(R.string.create),+            onConfirm = { actions.createFile(it); showNewFileDialog = false },+            onDismiss = { showNewFileDialog = false },+        )+    }+    itemForProperties?.let { item ->+        PropertiesDialog(item = item, onDismiss = { itemForProperties = null })     }      val focusManager = LocalFocusManager.current@@ -397,9 +666,21 @@ fun DirectoryScreen(         crumbs     } -    BackHandler(state.currentDirectory.absolutePath != root.absolutePath || state.selectedPaths.isNotEmpty() || state.zipPath != null) {-        pathBeingRenamed = null-        actions.handleBack()+    BackHandler(+        state.currentDirectory.absolutePath != root.absolutePath ||+            state.selectedPaths.isNotEmpty() ||+            state.zipPath != null ||+            state.isSearchActive ||+            isCategory+    ) {+        itemBeingRenamed = null+        if (state.isSearchActive) actions.setSearchActive(false) else actions.handleBack()+    }++    val zipToUnzip = remember(state.selectedPaths) {+        state.selectedPaths.singleOrNull()?.takeIf {+            !it.isDirectory && it.realFile != null && it.name.endsWith(".zip", ignoreCase = true)+        }     }      Scaffold(@@ -409,172 +690,363 @@ fun DirectoryScreen(                 interactionSource = remember { MutableInteractionSource() }, indication = null             ) {                 focusManager.clearFocus()-                pathBeingRenamed = null+                itemBeingRenamed = null                 actions.clearSelection()             }, snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = {-            TopAppBar(title = {-                Row(-                    verticalAlignment = Alignment.CenterVertically,-                    modifier = Modifier.horizontalScroll(rememberScrollState())-                ) {-                    breadcrumbs.forEachIndexed { index, crumb ->-                        var isBreadcrumbDraggingOver by remember(crumb) {-                            mutableStateOf(false)-                        }+            TopAppBar(navigationIcon = {+                if (!state.isSearchActive && state.selectedPaths.isEmpty()) {+                    IconButton(onClick = onOpenDrawer) { IconMenu() }+                }+            }, title = {+                if (state.isSearchActive) {+                    val searchFocus = remember { FocusRequester() }+                    TextField(+                        value = state.searchQuery,+                        onValueChange = { actions.setSearchQuery(it) },+                        placeholder = { Text(stringResource(R.string.search_files)) },+                        singleLine = true,+                        modifier = Modifier+                            .fillMaxWidth()+                            .focusRequester(searchFocus),+                    )+                    LaunchedEffect(Unit) { searchFocus.requestFocus() }+                } else if (isCategory) {+                    Text(state.categoryTitle ?: "", style = MaterialTheme.typography.titleLarge)+                } else {+                    Row(+                        verticalAlignment = Alignment.CenterVertically,+                        modifier = Modifier.horizontalScroll(rememberScrollState())+                    ) {+                        breadcrumbs.forEachIndexed { index, crumb ->+                            var isBreadcrumbDraggingOver by remember(crumb) {+                                mutableStateOf(false)+                            } -                        val canDrop = !isReadOnly && crumb.realFile != null && crumb.zipInternalPath == null+                            val canDrop = !isReadOnly && crumb.realFile != null && crumb.zipInternalPath == null -                        Box(-                            modifier = Modifier-                                .background(-                                    if (isBreadcrumbDraggingOver) MaterialTheme.colorScheme.primaryContainer.copy(-                                        alpha = 0.5f+                            Box(+                                modifier = Modifier+                                    .background(+                                        if (isBreadcrumbDraggingOver) MaterialTheme.colorScheme.primaryContainer.copy(+                                            alpha = 0.5f+                                        )+                                        else Color.Transparent, shape = MaterialTheme.shapes.small                                     )-                                    else Color.Transparent, shape = MaterialTheme.shapes.small+                                    .then(+                                        if (canDrop) {+                                            Modifier.dragAndDropTarget(+                                                shouldStartDragAndDrop = { event ->+                                                    event.mimeTypes().contains(+                                                        ClipDescription.MIMETYPE_TEXT_PLAIN+                                                    )+                                                },+                                                target = remember(crumb.realFile!!.absolutePath) {+                                                    dropTarget(+                                                        onDragStateChange = { isBreadcrumbDraggingOver = it },+                                                        onDrop = { sources -> actions.moveToBreadcrumb(sources, crumb.realFile) }+                                                    )+                                                })+                                        } else Modifier+                                    )+                                    .clickable {+                                        val rf = crumb.realFile+                                        if (rf != null) {+                                            if (state.zipPath != null) actions.navigateToZipParentRealFolder(rf)+                                            else actions.navigateTo(rf)+                                        } else {+                                            actions.navigateToZipInternalPath(crumb.zipInternalPath ?: "")+                                        }+                                    }+                                    .padding(4.dp)) {+                                Text(+                                    text = crumb.displayName, style = MaterialTheme.typography.titleLarge                                 )-                                .then(-                                    if (canDrop) {-                                        Modifier.dragAndDropTarget(-                                            shouldStartDragAndDrop = { event ->-                                                event.mimeTypes().contains(-                                                    ClipDescription.MIMETYPE_TEXT_PLAIN-                                                )-                                            },-                                            target = remember(crumb.realFile!!.absolutePath) {-                                                dropTarget(-                                                    onDragStateChange = { isBreadcrumbDraggingOver = it },-                                                    onDrop = { sources -> actions.moveToBreadcrumb(sources, crumb.realFile) }-                                                )-                                            })-                                    } else Modifier+                            }+                            if (index < breadcrumbs.size - 1) {+                                IconChevronRight(tint = MaterialTheme.colorScheme.outline)+                            }+                        }+                    }+                }+            }, actions = {+                if (state.isSearchActive) {+                    IconButton(onClick = { actions.setSearchActive(false) }) { IconClose() }+                } else if (state.selectedPaths.isNotEmpty()) {+                    IconButton(onClick = { actions.clearSelection() }) { IconClose() }+                    IconButton(onClick = { actions.deleteSelection() }) { IconDelete() }+                    IconButton(onClick = { showSelectionOverflow = true }) { IconMoreVert() }+                    DropdownMenu(+                        expanded = showSelectionOverflow,+                        onDismissRequest = { showSelectionOverflow = false },+                    ) {+                        DropdownMenuItem(+                            text = { Text(stringResource(R.string.copy)) },+                            leadingIcon = { IconCopy() },+                            onClick = { showSelectionOverflow = false; actions.copySelection() },+                        )+                        DropdownMenuItem(+                            text = { Text(stringResource(R.string.cut)) },+                            leadingIcon = { IconArchive() },+                            onClick = { showSelectionOverflow = false; actions.cutSelection() },+                        )+                        DropdownMenuItem(+                            text = { Text(stringResource(R.string.share)) },+                            leadingIcon = { IconShare() },+                            onClick = { showSelectionOverflow = false; actions.shareSelection() },+                        )+                        val single = state.selectedPaths.singleOrNull()+                        if (single != null && !single.isDirectory) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.open_with)) },+                                leadingIcon = { IconShare() },+                                onClick = { showSelectionOverflow = false; actions.openWith(single) },+                            )+                        }+                        if (single != null) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.rename)) },+                                leadingIcon = { IconEdit() },+                                onClick = {+                                    showSelectionOverflow = false+                                    itemBeingRenamed = single+                                },+                            )+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.properties)) },+                                leadingIcon = { IconInfo() },+                                onClick = { showSelectionOverflow = false; itemForProperties = single },+                            )+                        }+                        if (single != null && single.isDirectory && single.realFile != null) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.add_bookmark)) },+                                leadingIcon = { IconStar() },+                                onClick = { showSelectionOverflow = false; actions.addBookmark(single) },+                            )+                        }+                        if (canModifyHere) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.archive)) },+                                leadingIcon = { IconArchive() },+                                onClick = {+                                    showSelectionOverflow = false+                                    archiveName =+                                        if (state.selectedPaths.size == 1) "${state.selectedPaths.first().name}.zip"+                                        else "archive.zip"+                                    showArchiveDialog = true+                                },+                            )+                        }+                        if (zipToUnzip != null) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.archive_selection)) },+                                leadingIcon = { IconUnarchive() },+                                onClick = { showSelectionOverflow = false; onPickUnzipDestination() },+                            )+                        }+                        if (state.hasIncomingUris) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.files_saved)) },+                                leadingIcon = { IconSave() },+                                onClick = { showSelectionOverflow = false; actions.saveIncomingUris() },+                            )+                        }+                    }+                } else {+                    if (state.hasIncomingUris && !isReadOnly) {+                        IconButton(onClick = { actions.saveIncomingUris() }) { IconSave() }+                    }+                    IconButton(onClick = { actions.setSearchActive(true) }) { IconSearch() }+                    IconButton(onClick = { showOverflow = true }) { IconMoreVert() }+                    DropdownMenu(+                        expanded = showOverflow,+                        onDismissRequest = { showOverflow = false },+                    ) {+                        SortBy.entries.forEach { option ->+                            DropdownMenuItem(+                                text = { Text(sortLabel(option)) },+                                leadingIcon = { if (state.sortBy == option) IconCheck() },+                                onClick = { showOverflow = false; actions.setSortBy(option) },+                            )+                        }+                        HorizontalDivider()+                        DropdownMenuItem(+                            text = { Text(stringResource(R.string.sort_ascending)) },+                            leadingIcon = { if (state.sortAscending) IconCheck() },+                            onClick = { showOverflow = false; actions.setSortAscending(true) },+                        )+                        DropdownMenuItem(+                            text = { Text(stringResource(R.string.sort_descending)) },+                            leadingIcon = { if (!state.sortAscending) IconCheck() },+                            onClick = { showOverflow = false; actions.setSortAscending(false) },+                        )+                        DropdownMenuItem(+                            text = {+                                Text(+                                    stringResource(+                                        if (state.viewMode == ViewMode.LIST) R.string.grid_view+                                        else R.string.list_view+                                    )                                 )-                                .clickable {-                                    val rf = crumb.realFile-                                    if (rf != null) {-                                        if (state.zipPath != null) actions.navigateToZipParentRealFolder(rf)-                                        else actions.navigateTo(rf)-                                    } else {-                                        actions.navigateToZipInternalPath(crumb.zipInternalPath ?: "")-                                    }-                                }-                                .padding(4.dp)) {-                            Text(-                                text = crumb.displayName, style = MaterialTheme.typography.titleLarge+                            },+                            leadingIcon = {+                                if (state.viewMode == ViewMode.LIST) IconGrid() else IconList()+                            },+                            onClick = { showOverflow = false; actions.toggleViewMode() },+                        )+                        DropdownMenuItem(+                            text = {+                                Text(+                                    stringResource(+                                        if (state.showHidden) R.string.hide_hidden else R.string.show_hidden+                                    )+                                )+                            },+                            leadingIcon = { if (state.showHidden) IconVisibilityOff() else IconVisible() },+                            onClick = { showOverflow = false; actions.toggleHidden() },+                        )+                        if (!isReadOnly) {+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.select_all)) },+                                onClick = { showOverflow = false; actions.selectAll() },                             )                         }-                        if (index < breadcrumbs.size - 1) {-                            IconChevronRight(tint = MaterialTheme.colorScheme.outline)+                        if (canModifyHere) {+                            HorizontalDivider()+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.new_folder)) },+                                leadingIcon = { IconNewFolder() },+                                onClick = { showOverflow = false; showNewFolderDialog = true },+                            )+                            DropdownMenuItem(+                                text = { Text(stringResource(R.string.new_file)) },+                                leadingIcon = { IconNewFile() },+                                onClick = { showOverflow = false; showNewFileDialog = true },+                            )                         }                     }                 }-            }, actions = {-                if (state.selectedPaths.isNotEmpty()) {-                    IconButton(-                        onClick = { actions.clearSelection() }) { IconClose() }+            })+        }) { padding ->+        val query = state.searchQuery.trim()+        fun matches(item: FileBrowserItem) =+            query.isEmpty() || item.name.contains(query, ignoreCase = true)+        val allItems = (state.directories + state.files).filter(::matches)++        Column(Modifier.fillMaxSize().padding(padding)) {+            // Paste bar: shown when the clipboard has files and we can write here.+            if (state.clipboardCount > 0 && canModifyHere && state.selectedPaths.isEmpty() && !state.isSearchActive) {+                Surface(color = MaterialTheme.colorScheme.secondaryContainer) {+                    Row(+                        modifier = Modifier+                            .fillMaxWidth()+                            .padding(horizontal = 16.dp, vertical = 8.dp),+                        verticalAlignment = Alignment.CenterVertically,+                    ) {+                        Text(+                            stringResource(R.string.ready_to_paste, state.clipboardCount),+                            modifier = Modifier.weight(1f),+                        )+                        TextButton(onClick = { actions.pasteHere() }) { Text(stringResource(R.string.paste)) }+                        IconButton(onClick = { actions.clearClipboard() }) { IconClose() }+                    }                 }-                if (state.hasIncomingUris && !isReadOnly) {-                    IconButton(-                        onClick = { actions.saveIncomingUris() }) { IconSave() }+            }++            val onItemClick: (FileBrowserItem) -> Unit = { child ->+                if (state.selectedPaths.isNotEmpty()) {+                    actions.toggleSelection(child)+                } else if (child.isDirectory) {+                    if (child.realFile != null) actions.navigateTo(child.realFile)+                    else actions.navigateIntoZipDir(child.name)+                } else if (child.name.endsWith(".zip", ignoreCase = true) && child.realFile != null) {+                    actions.openZipFile(child)+                } else {+                    actions.openFile(child)                 }+            }+            val onItemLongClick: (FileBrowserItem) -> Unit = { child ->                 if (!isReadOnly) {-                    if (state.selectedPaths.isNotEmpty()) {-                        IconButton(-                            onClick = {-                                archiveName =-                                    if (state.selectedPaths.size == 1) "${state.selectedPaths.first().name}.zip"-                                    else "archive.zip"-                                showArchiveDialog = true-                            }) { IconArchive() }-                    }-                    if (zipToUnzip != null) {-                        IconButton(onClick = onPickUnzipDestination) {-                            IconUnarchive()-                        }-                    }-                    if (state.selectedPaths.size == 1) {-                        IconButton(-                            onClick = { pathBeingRenamed = state.selectedPaths.first() }) { IconEdit() }+                    itemBeingRenamed = null+                    actions.toggleSelection(child)+                }+            }++            if (allItems.isEmpty()) {+                Box(+                    Modifier.weight(1f).fillMaxWidth(),+                    contentAlignment = Alignment.Center,+                ) {+                    Text(+                        stringResource(R.string.no_files),+                        color = MaterialTheme.colorScheme.outline,+                    )+                }+            } else if (state.viewMode == ViewMode.GRID) {+                LazyVerticalGrid(+                    columns = GridCells.Adaptive(minSize = 104.dp),+                    modifier = Modifier.weight(1f).fillMaxWidth(),+                ) {+                    gridItems(allItems, key = { it.key }) { child ->+                        GridItem(+                            file = child,+                            isSelected = state.selectedPaths.any { it.key == child.key },+                            onClick = { onItemClick(child) },+                            onLongClick = { onItemLongClick(child) },+                        )                     }-                    if (state.selectedPaths.isNotEmpty()) {-                        IconButton(-                            onClick = { actions.deleteSelection() }) { IconDelete() }+                }+            } else {+                LazyColumn(Modifier.weight(1f)) {+                    items(allItems, key = { it.key }) { child ->+                        val isSelected = state.selectedPaths.any { it.key == child.key }+                        DirectoryItem(+                            file = child,+                            isSelected = isSelected,+                            isReadOnly = isReadOnly,+                            onLongClick = { onItemLongClick(child) },+                            onClick = { onItemClick(child) },+                            onMove = { sources ->+                                if (!isReadOnly && child.isDirectory && child.realFile != null) {+                                    actions.moveInto(sources, child.realFile)+                                }+                            },+                            onStartDrag = {+                                if (isReadOnly) emptyList()+                                else if (state.selectedPaths.any { it.key == child.key }) state.selectedPaths.mapNotNull { it.realFile }.toList()+                                else listOfNotNull(child.realFile)+                            })+                        HorizontalDivider(+                            thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant+                        )                     }                 }-            })-        }) { padding ->-        LazyColumn(Modifier.padding(padding)) {-            val allItems =-                state.directories.sortedBy { it.name.lowercase() } + state.files.sortedBy { it.name.lowercase() }--            items(allItems, key = { it.key }) { child ->-                val isSelected = state.selectedPaths.any { it.key == child.key }-                val isEditing = pathBeingRenamed?.key == child.key--                DirectoryItem(-                    file = child,-                    isEditing = isEditing,-                    isSelected = isSelected,-                    isReadOnly = isReadOnly,-                    onRename = { newName ->-                        pathBeingRenamed = null-                        actions.rename(child, newName)-                    },-                    onToggleSelection = {-                        if (isReadOnly) return@DirectoryItem-                        if (pathBeingRenamed != null) pathBeingRenamed = null-                        if (!isSelected) {-                            actions.addToSelection(child)-                        }-                    },-                    onClick = {-                        if (state.selectedPaths.isNotEmpty()) {-                            if (isSelected && pathBeingRenamed?.key == child.key) {-                                pathBeingRenamed = null-                            }-                            actions.toggleSelection(child)-                        } else if (child.isDirectory) {-                            if (child.realFile != null) actions.navigateTo(child.realFile)-                            else actions.navigateIntoZipDir(child.name)-                        } else if (child.name.endsWith(".zip", ignoreCase = true) && child.realFile != null) {-                            actions.openZipFile(child)-                        } else {-                            actions.openFile(child)-                        }-                    },-                    onMove = { sources ->-                        if (!isReadOnly && child.isDirectory && child.realFile != null) {-                            actions.moveInto(sources, child.realFile)-                        }-                    },-                    onStartDrag = {-                        if (isReadOnly) emptyList()-                        else if (state.selectedPaths.any { it.key == child.key }) state.selectedPaths.mapNotNull { it.realFile }.toList()-                        else listOfNotNull(child.realFile)-                    })-                HorizontalDivider(-                    thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant-                )             }         }     } } +@Composable+private fun sortLabel(sortBy: SortBy): String = stringResource(+    when (sortBy) {+        SortBy.NAME -> R.string.sort_name+        SortBy.DATE -> R.string.sort_date+        SortBy.SIZE -> R.string.sort_size+        SortBy.TYPE -> R.string.sort_type+    }+)+ @OptIn(ExperimentalFoundationApi::class) @Composable fun DirectoryItem(     file: FileBrowserItem,-    isEditing: Boolean,     isSelected: Boolean,     isReadOnly: Boolean,-    onRename: (String) -> Unit,-    onToggleSelection: () -> Unit,+    onLongClick: () -> Unit,     onClick: () -> Unit,     onMove: (List<File>) -> Unit,     onStartDrag: () -> List<File> ) {-    var editedName by remember(isEditing) { mutableStateOf(file.name) }-    val focusRequester = remember { FocusRequester() }-    val keyboard = LocalSoftwareKeyboardController.current     var isDraggingOver by remember { mutableStateOf(false) }     val currentOnMove by rememberUpdatedState(onMove)     val currentOnStartDrag by rememberUpdatedState(onStartDrag)@@ -643,38 +1115,328 @@ fun DirectoryItem(                     })                 } else Modifier             )-            .combinedClickable(onClick = onClick, onLongClick = onToggleSelection)+            .combinedClickable(onClick = onClick, onLongClick = onLongClick)     ) {         ListItem(-            content = {-                if (isEditing) {-                    TextField(-                        value = editedName,-                        onValueChange = { editedName = it },-                        modifier = Modifier-                            .focusRequester(focusRequester)-                            .fillMaxWidth(),-                        singleLine = true,-                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),-                        keyboardActions = KeyboardActions(onDone = { onRename(editedName) })-                    )-                    LaunchedEffect(Unit) {-                        focusRequester.requestFocus()-                        keyboard?.show()-                    }-                } else {-                    Text(file.name.ifEmpty { "/" })-                }-            }, leadingContent = {-                val iconTint = if (isSelected) MaterialTheme.colorScheme.primary-                else MaterialTheme.colorScheme.outline-                if (file.isDirectory) IconFolder(tint = iconTint)-                else IconFile(tint = iconTint)-            }, supportingContent = {+            content = { Text(file.name.ifEmpty { "/" }) },+            leadingContent = { FileLeading(file, isSelected, 40.dp) },+            supportingContent = {                 if (!file.isDirectory) {                     file.size?.let { size -> Text(Formatter.formatShortFileSize(context, size)) }                 }-            }, colors = ListItemDefaults.colors(containerColor = Color.Transparent)+            },+            colors = ListItemDefaults.colors(containerColor = Color.Transparent)         )     } }++@OptIn(ExperimentalFoundationApi::class)+@Composable+fun GridItem(+    file: FileBrowserItem,+    isSelected: Boolean,+    onClick: () -> Unit,+    onLongClick: () -> Unit,+) {+    Column(+        modifier = Modifier+            .fillMaxWidth()+            .combinedClickable(onClick = onClick, onLongClick = onLongClick)+            .background(+                if (isSelected) MaterialTheme.colorScheme.surfaceVariant else Color.Transparent+            )+            .padding(8.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        Box(Modifier.size(56.dp), contentAlignment = Alignment.Center) {+            FileLeading(file, isSelected, 56.dp)+        }+        Spacer(Modifier.size(6.dp))+        Text(+            text = file.name.ifEmpty { "/" },+            style = MaterialTheme.typography.bodySmall,+            maxLines = 2,+            overflow = TextOverflow.Ellipsis,+            textAlign = TextAlign.Center,+        )+    }+}++// ---- Home screen ----++/** Binds [FilesViewModel] to the stateless [HomeScreen]. */+@Composable+fun HomeScreenBinder(viewModel: FilesViewModel, onOpenDrawer: () -> Unit = {}) {+    val context = LocalContext.current+    val resources = LocalResources.current+    val snackbarHostState = remember { SnackbarHostState() }++    val storage by viewModel.storage.collectAsState()+    val recents by viewModel.recents.collectAsState()+    val bookmarks by viewModel.bookmarks.collectAsState()++    LaunchedEffect(snackbarHostState) {+        viewModel.snackbarMessages.collect { snackbarHostState.showSnackbar(it) }+    }+    LaunchedEffect(Unit) {+        viewModel.intents.collect { intent ->+            try {+                context.startActivity(intent)+            } catch (_: Exception) {+                viewModel.showMessage(resources.getString(R.string.no_app_found_to_open_file))+            }+        }+    }++    HomeScreen(+        home = HomeUiState(+            rootDisplayName = Build.MODEL,+            storage = storage,+            recents = recents,+            bookmarks = bookmarks,+        ),+        actions = viewModel,+        snackbarHostState = snackbarHostState,+        onOpenDrawer = onOpenDrawer,+    )+}++/** The home landing screen: storage meter, category shortcuts, bookmarks, and recents. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun HomeScreen(+    home: HomeUiState,+    actions: FilesActions,+    snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },+    onOpenDrawer: () -> Unit = {},+) {+    val context = LocalContext.current+    Scaffold(+        snackbarHost = { SnackbarHost(snackbarHostState) },+        topBar = {+            TopAppBar(+                navigationIcon = { IconButton(onClick = onOpenDrawer) { IconMenu() } },+                title = { Text(stringResource(R.string.app_name)) },+            )+        },+    ) { padding ->+        LazyColumn(Modifier.fillMaxSize().padding(padding)) {+            home.storage?.let { s -> item { StorageCard(s) } }++            item {+                HomeRow(+                    leading = { IconFolder(tint = MaterialTheme.colorScheme.primary) },+                    title = stringResource(R.string.internal_storage),+                    subtitle = home.storage?.let { Formatter.formatShortFileSize(context, it.totalBytes) },+                    onClick = { actions.openInternalStorage() },+                )+            }++            item { SectionHeader(stringResource(R.string.categories)) }+            item {+                Row(+                    Modifier+                        .fillMaxWidth()+                        .horizontalScroll(rememberScrollState())+                        .padding(horizontal = 12.dp),+                    horizontalArrangement = Arrangement.spacedBy(4.dp),+                ) {+                    CategoryTile(stringResource(R.string.cat_images), { IconImage(tint = COLOR_IMAGE) }) { actions.openCategory(FileCategory.IMAGES) }+                    CategoryTile(stringResource(R.string.cat_videos), { IconVideoCamera(tint = COLOR_VIDEO) }) { actions.openCategory(FileCategory.VIDEOS) }+                    CategoryTile(stringResource(R.string.cat_audio), { IconLibraryMusic(tint = COLOR_AUDIO) }) { actions.openCategory(FileCategory.AUDIO) }+                    CategoryTile(stringResource(R.string.cat_documents), { IconDescription(tint = COLOR_DOC) }) { actions.openCategory(FileCategory.DOCUMENTS) }+                    CategoryTile(stringResource(R.string.cat_downloads), { IconDownload(tint = COLOR_APK) }) { actions.openCategory(FileCategory.DOWNLOADS) }+                }+            }++            if (home.bookmarks.isNotEmpty()) {+                item { SectionHeader(stringResource(R.string.bookmarks)) }+                items(home.bookmarks, key = { "bm:" + it.key }) { bm ->+                    HomeRow(+                        leading = { IconFolder(tint = MaterialTheme.colorScheme.outline) },+                        title = bm.name,+                        subtitle = null,+                        onClick = { bm.realFile?.let { actions.openBookmark(it) } },+                        trailing = {+                            IconButton(onClick = { bm.realFile?.let { actions.removeBookmark(it) } }) { IconClose() }+                        },+                    )+                }+            }++            if (home.recents.isNotEmpty()) {+                item { SectionHeader(stringResource(R.string.recent_files)) }+                items(home.recents, key = { "rc:" + it.key }) { r ->+                    HomeRow(+                        leading = { FileLeading(r, false, 40.dp) },+                        title = r.name,+                        subtitle = r.size?.let { Formatter.formatShortFileSize(context, it) },+                        onClick = { actions.openFile(r) },+                    )+                }+            }+        }+    }+}++@Composable+private fun StorageCard(storage: StorageInfo) {+    val context = LocalContext.current+    Card(modifier = Modifier.fillMaxWidth().padding(16.dp)) {+        Column(Modifier.padding(16.dp)) {+            Text(stringResource(R.string.internal_storage), style = MaterialTheme.typography.titleMedium)+            Spacer(Modifier.size(10.dp))+            val fraction = if (storage.totalBytes > 0) {+                (storage.usedBytes.toFloat() / storage.totalBytes).coerceIn(0f, 1f)+            } else 0f+            LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth())+            Spacer(Modifier.size(10.dp))+            Text(+                stringResource(+                    R.string.storage_usage,+                    Formatter.formatShortFileSize(context, storage.usedBytes),+                    Formatter.formatShortFileSize(context, storage.totalBytes),+                ),+                style = MaterialTheme.typography.bodySmall,+            )+        }+    }+}++@Composable+private fun CategoryTile(label: String, icon: @Composable () -> Unit, onClick: () -> Unit) {+    Column(+        modifier = Modifier+            .clip(RoundedCornerShape(12.dp))+            .clickable(onClick = onClick)+            .padding(12.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        Box(Modifier.size(44.dp), contentAlignment = Alignment.Center) { icon() }+        Spacer(Modifier.size(4.dp))+        Text(label, style = MaterialTheme.typography.bodySmall)+    }+}++@Composable+private fun HomeRow(+    leading: @Composable () -> Unit,+    title: String,+    subtitle: String?,+    onClick: () -> Unit,+    trailing: (@Composable () -> Unit)? = null,+) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .clickable(onClick = onClick)+            .padding(horizontal = 16.dp, vertical = 12.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) { leading() }+        Spacer(Modifier.width(16.dp))+        Column(Modifier.weight(1f)) {+            Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)+            subtitle?.let {+                Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.outline)+            }+        }+        trailing?.invoke()+    }+}++@Composable+private fun SectionHeader(text: String) {+    Text(+        text,+        style = MaterialTheme.typography.titleSmall,+        color = MaterialTheme.colorScheme.primary,+        modifier = Modifier.padding(start = 16.dp, top = 16.dp, bottom = 4.dp),+    )+}++// ---- Shared dialogs ----++@Composable+private fun NameDialog(+    title: String,+    label: String,+    initial: String,+    confirmLabel: String,+    onConfirm: (String) -> Unit,+    onDismiss: () -> Unit,+) {+    var name by remember { mutableStateOf(initial) }+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(title) },+        text = {+            TextField(+                value = name,+                onValueChange = { name = it },+                label = { Text(label) },+                singleLine = true,+                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+                keyboardActions = KeyboardActions(onDone = { if (name.isNotBlank()) onConfirm(name) }),+            )+        },+        confirmButton = {+            TextButton(onClick = { if (name.isNotBlank()) onConfirm(name) }) { Text(confirmLabel) }+        },+        dismissButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }+        },+    )+}++@Composable+private fun PropertiesDialog(item: FileBrowserItem, onDismiss: () -> Unit) {+    val context = LocalContext.current+    var childCount by remember(item.key) { mutableStateOf<Int?>(null) }+    val realFile = item.realFile+    if (item.isDirectory && realFile != null) {+        LaunchedEffect(item.key) {+            childCount = withContext(Dispatchers.IO) { realFile.listFiles()?.size ?: 0 }+        }+    }+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(item.name.ifEmpty { "/" }) },+        text = {+            Column {+                realFile?.let { PropRow(stringResource(R.string.prop_path), it.absolutePath) }+                PropRow(+                    stringResource(R.string.prop_type),+                    stringResource(if (item.isDirectory) R.string.type_folder else R.string.type_file),+                )+                if (item.isDirectory) {+                    PropRow(+                        stringResource(R.string.prop_items),+                        childCount?.let { stringResource(R.string.items_count, it) } ?: "…",+                    )+                } else {+                    item.size?.let {+                        PropRow(stringResource(R.string.prop_size), Formatter.formatShortFileSize(context, it))+                    }+                }+                if (item.lastModified > 0) {+                    PropRow(+                        stringResource(R.string.prop_modified),+                        DateFormat.getDateTimeInstance().format(Date(item.lastModified)),+                    )+                }+            }+        },+        confirmButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.close)) }+        },+    )+}++@Composable+private fun PropRow(label: String, value: String) {+    Column(Modifier.padding(vertical = 4.dp)) {+        Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.outline)+        Text(value, style = MaterialTheme.typography.bodyMedium)+    }+}
files/src/main/java/com/vayunmathur/files/util/FilesUiContract.kt
diff --git a/files/src/main/java/com/vayunmathur/files/util/FilesUiContract.kt b/files/src/main/java/com/vayunmathur/files/util/FilesUiContract.ktindex ef7a63f6f1..3975603887 100644--- a/files/src/main/java/com/vayunmathur/files/util/FilesUiContract.kt+++ b/files/src/main/java/com/vayunmathur/files/util/FilesUiContract.kt@@ -11,6 +11,20 @@ import java.io.File  * dependency runs one way, and [FilesViewModel] implements [FilesActions] directly.  */ +/** How the current directory's entries are ordered. */+enum class SortBy { NAME, DATE, SIZE, TYPE }++/** List vs. grid presentation of the current directory. */+enum class ViewMode { LIST, GRID }++/** A home-screen shortcut that collects files of one kind from across storage. */+enum class FileCategory { IMAGES, VIDEOS, AUDIO, DOCUMENTS, DOWNLOADS }++/** Storage volume usage, for the home screen meter. */+data class StorageInfo(val totalBytes: Long, val freeBytes: Long) {+    val usedBytes: Long get() = (totalBytes - freeBytes).coerceAtLeast(0)+}+ /** Everything the directory browser draws. */ data class FilesUiState(     val rootDirectory: File,@@ -28,6 +42,27 @@ data class FilesUiState(     val selectedPaths: Set<FileBrowserItem> = emptySet(),     /** True while files shared into the app are waiting to be saved here. */     val hasIncomingUris: Boolean = false,+    val sortBy: SortBy = SortBy.NAME,+    val sortAscending: Boolean = true,+    val viewMode: ViewMode = ViewMode.LIST,+    /** Non-empty while the search field filters the current listing by name. */+    val searchQuery: String = "",+    val isSearchActive: Boolean = false,+    /** Number of files on the copy/cut clipboard (0 = nothing to paste). */+    val clipboardCount: Int = 0,+    /** True when the clipboard holds a cut (move on paste) rather than a copy. */+    val clipboardIsCut: Boolean = false,+    val showHidden: Boolean = false,+    /** Non-null while showing a category result list (e.g. "Images"); [directories] is empty. */+    val categoryTitle: String? = null,+)++/** The state the home screen draws (storage meter, shortcuts, recents, bookmarks). */+data class HomeUiState(+    val rootDisplayName: String,+    val storage: StorageInfo? = null,+    val recents: List<FileBrowserItem> = emptyList(),+    val bookmarks: List<FileBrowserItem> = emptyList(), )  /**@@ -46,6 +81,7 @@ interface FilesActions {     fun clearSelection() {}     fun addToSelection(item: FileBrowserItem) {}     fun toggleSelection(item: FileBrowserItem) {}+    fun selectAll() {}      fun rename(item: FileBrowserItem, newName: String) {}     fun deleteSelection() {}@@ -54,9 +90,40 @@ interface FilesActions {      fun openZipFile(item: FileBrowserItem) {}     fun openFile(item: FileBrowserItem) {}+    fun openWith(item: FileBrowserItem) {}+    fun shareSelection() {}     fun archive(archiveName: String) {}     fun saveIncomingUris() {} +    // ---- Sort & view ----+    fun setSortBy(sortBy: SortBy) {}+    fun toggleSortDirection() {}+    fun setSortAscending(ascending: Boolean) {}+    fun toggleViewMode() {}+    fun toggleHidden() {}++    // ---- Search ----+    fun setSearchActive(active: Boolean) {}+    fun setSearchQuery(query: String) {}++    // ---- Clipboard (copy/cut/paste) ----+    fun copySelection() {}+    fun cutSelection() {}+    fun pasteHere() {}+    fun clearClipboard() {}++    // ---- Create ----+    fun createFolder(name: String) {}+    fun createFile(name: String) {}++    // ---- Home / categories / bookmarks ----+    fun goHome() {}+    fun openInternalStorage() {}+    fun openCategory(category: FileCategory) {}+    fun openBookmark(path: File) {}+    fun addBookmark(item: FileBrowserItem) {}+    fun removeBookmark(path: File) {}+     companion object {         val Noop: FilesActions = object : FilesActions {}     }
files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt
diff --git a/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt b/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.ktindex 1e51eedd0a..ef85a333a0 100644--- a/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt+++ b/files/src/main/java/com/vayunmathur/files/util/FilesViewModel.kt@@ -6,6 +6,8 @@ import android.content.Intent import android.net.Uri import android.os.Environment import android.os.FileObserver+import android.os.StatFs+import android.provider.MediaStore import android.provider.OpenableColumns import android.webkit.MimeTypeMap import androidx.core.content.FileProvider@@ -40,6 +42,7 @@ data class FileBrowserItem(     val realFile: File?,     val zipInnerPath: String?,     val key: String,+    val lastModified: Long = 0L, )  class FilesViewModel(application: Application) : AndroidViewModel(application), FilesActions {@@ -54,7 +57,10 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),         val granted = Environment.isExternalStorageManager()         if (_isFilesGranted.value != granted) {             _isFilesGranted.value = granted-            if (granted) loadDirectory()+            if (granted) {+                loadDirectory()+                loadHome()+            }         }     } @@ -109,6 +115,400 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),         }     } +    override fun selectAll() {+        if (isZipMode()) return+        val (dirs, files) = _entries.value+        _selectedPaths.value = (dirs + files).toSet()+    }++    // ---- Sort, view mode, search ----+    private val _sortBy = MutableStateFlow(+        runCatching { SortBy.valueOf(prefs.getString("sort_by", null) ?: "NAME") }+            .getOrDefault(SortBy.NAME)+    )+    val sortBy: StateFlow<SortBy> = _sortBy.asStateFlow()++    private val _sortAscending = MutableStateFlow(prefs.getBoolean("sort_ascending", true))+    val sortAscending: StateFlow<Boolean> = _sortAscending.asStateFlow()++    private val _viewMode = MutableStateFlow(+        runCatching { ViewMode.valueOf(prefs.getString("view_mode", null) ?: "LIST") }+            .getOrDefault(ViewMode.LIST)+    )+    val viewMode: StateFlow<ViewMode> = _viewMode.asStateFlow()++    private val _searchQuery = MutableStateFlow("")+    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()++    private val _isSearchActive = MutableStateFlow(false)+    val isSearchActive: StateFlow<Boolean> = _isSearchActive.asStateFlow()++    override fun setSortBy(sortBy: SortBy) {+        if (_sortBy.value == sortBy) return+        _sortBy.value = sortBy+        prefs.edit { putString("sort_by", sortBy.name) }+        loadDirectory()+    }++    override fun toggleSortDirection() {+        setSortAscending(!_sortAscending.value)+    }++    override fun setSortAscending(ascending: Boolean) {+        if (_sortAscending.value == ascending) return+        _sortAscending.value = ascending+        prefs.edit { putBoolean("sort_ascending", ascending) }+        loadDirectory()+    }++    private val downloadsDir: File get() = File(rootDirectory, "Download")++    /**+     * Apply the sensible default sort when *entering* a folder: the Downloads folder shows+     * newest-first (by date), which is what people usually want there; every other folder+     * uses the persisted global sort. This only sets the in-memory sort, so an explicit+     * choice via the menu (which persists) still wins while you stay in the folder.+     */+    private fun applyDirDefaults(path: File) {+        if (path.absolutePath == downloadsDir.absolutePath) {+            _sortBy.value = SortBy.DATE+            _sortAscending.value = false+        } else {+            _sortBy.value = runCatching {+                SortBy.valueOf(prefs.getString("sort_by", null) ?: "NAME")+            }.getOrDefault(SortBy.NAME)+            _sortAscending.value = prefs.getBoolean("sort_ascending", true)+        }+    }++    override fun toggleViewMode() {+        val next = if (_viewMode.value == ViewMode.LIST) ViewMode.GRID else ViewMode.LIST+        _viewMode.value = next+        prefs.edit { putString("view_mode", next.name) }+    }++    override fun setSearchActive(active: Boolean) {+        _isSearchActive.value = active+        if (!active) _searchQuery.value = ""+    }++    override fun setSearchQuery(query: String) {+        _searchQuery.value = query+    }++    // ---- Hidden files ----+    private val _showHidden = MutableStateFlow(prefs.getBoolean("show_hidden", false))+    val showHidden: StateFlow<Boolean> = _showHidden.asStateFlow()++    override fun toggleHidden() {+        val next = !_showHidden.value+        _showHidden.value = next+        prefs.edit { putBoolean("show_hidden", next) }+        loadDirectory()+    }++    // ---- Create ----+    override fun createFolder(name: String) {+        if (isZipMode() || name.isBlank()) return+        viewModelScope.launch(Dispatchers.IO) {+            try {+                val dir = uniqueDestination(_currentDirectory.value, name.trim())+                if (dir.mkdirs()) loadDirectory()+                else emit(getApplication<Application>().getString(R.string.create_failed))+            } catch (e: Exception) {+                emitMoveFailed(e)+            }+        }+    }++    override fun createFile(name: String) {+        if (isZipMode() || name.isBlank()) return+        viewModelScope.launch(Dispatchers.IO) {+            try {+                val file = uniqueDestination(_currentDirectory.value, name.trim())+                if (file.createNewFile()) loadDirectory()+                else emit(getApplication<Application>().getString(R.string.create_failed))+            } catch (e: Exception) {+                emitMoveFailed(e)+            }+        }+    }++    override fun openWith(item: FileBrowserItem) {+        val ctx = getApplication<Application>()+        val file = item.realFile ?: return+        val uri = FileProvider.getUriForFile(ctx, "${ctx.packageName}.fileprovider", file)+        val view = Intent(Intent.ACTION_VIEW).apply {+            setDataAndType(uri, mimeFor(file))+            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)+        }+        val chooser = Intent.createChooser(view, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        viewModelScope.launch { _intents.emit(chooser) }+    }++    // ---- 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()++    private val _storage = MutableStateFlow<StorageInfo?>(null)+    val storage: StateFlow<StorageInfo?> = _storage.asStateFlow()++    private val _recents = MutableStateFlow<List<FileBrowserItem>>(emptyList())+    val recents: StateFlow<List<FileBrowserItem>> = _recents.asStateFlow()++    private val _bookmarks = MutableStateFlow(loadBookmarks())+    val bookmarks: StateFlow<List<FileBrowserItem>> = _bookmarks.asStateFlow()++    fun loadHome() {+        viewModelScope.launch(Dispatchers.IO) {+            _storage.value = readStorage()+            _bookmarks.value = loadBookmarks()+            _recents.value = queryRecents()+        }+    }++    override fun goHome() {+        _atHome.value = true+        _categoryTitle.value = null+        _zipPath.value = null+        _zipInternalPath.value = ""+        clearSelection()+        observerJob?.cancel()+        loadHome()+    }++    override fun openInternalStorage() {+        _categoryTitle.value = null+        navigateTo(rootDirectory)+    }++    override fun openBookmark(path: File) {+        _categoryTitle.value = null+        navigateTo(path)+    }++    override fun openCategory(category: FileCategory) {+        if (category == FileCategory.DOWNLOADS) {+            val dl = File(rootDirectory, "Download")+            openBookmark(if (dl.isDirectory) dl else rootDirectory)+            return+        }+        _atHome.value = false+        _zipPath.value = null+        _categoryTitle.value = getApplication<Application>().getString(categoryLabel(category))+        clearSelection()+        observerJob?.cancel()+        viewModelScope.launch(Dispatchers.IO) {+            _entries.value = emptyList<FileBrowserItem>() to sortItems(queryCategory(category))+        }+    }++    override fun addBookmark(item: FileBrowserItem) {+        val path = item.realFile ?: return+        val set = (prefs.getStringSet("bookmarks", emptySet()) ?: emptySet()).toMutableSet()+        set.add(path.absolutePath)+        prefs.edit { putStringSet("bookmarks", set) }+        _bookmarks.value = loadBookmarks()+        emit(getApplication<Application>().getString(R.string.bookmark_added))+    }++    override fun removeBookmark(path: File) {+        val set = (prefs.getStringSet("bookmarks", emptySet()) ?: emptySet()).toMutableSet()+        set.remove(path.absolutePath)+        prefs.edit { putStringSet("bookmarks", set) }+        _bookmarks.value = loadBookmarks()+    }++    private fun loadBookmarks(): List<FileBrowserItem> {+        val saved = prefs.getStringSet("bookmarks", emptySet()) ?: emptySet()+        return saved.map { File(it) }+            .filter { it.exists() }+            .sortedBy { it.name.lowercase() }+            .map { it.toItem() }+    }++    private fun readStorage(): StorageInfo = try {+        val stat = StatFs(rootDirectory.absolutePath)+        StorageInfo(totalBytes = stat.totalBytes, freeBytes = stat.availableBytes)+    } catch (_: Exception) {+        StorageInfo(0, 0)+    }++    private fun categoryLabel(c: FileCategory): Int = when (c) {+        FileCategory.IMAGES -> R.string.cat_images+        FileCategory.VIDEOS -> R.string.cat_videos+        FileCategory.AUDIO -> R.string.cat_audio+        FileCategory.DOCUMENTS -> R.string.cat_documents+        FileCategory.DOWNLOADS -> R.string.cat_downloads+    }++    private fun queryCategory(category: FileCategory): List<FileBrowserItem> = when (category) {+        FileCategory.IMAGES -> queryMedia(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, 2000)+        FileCategory.VIDEOS -> queryMedia(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, 2000)+        FileCategory.AUDIO -> queryMedia(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, 2000)+        FileCategory.DOCUMENTS -> {+            val mimes = arrayOf(+                "application/pdf", "application/msword",+                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+                "application/vnd.ms-excel",+                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+                "application/vnd.ms-powerpoint",+                "application/vnd.openxmlformats-officedocument.presentationml.presentation",+                "text/plain", "text/markdown", "text/csv", "application/rtf",+            )+            val selection = mimes.joinToString(" OR ") { "${MediaStore.Files.FileColumns.MIME_TYPE}=?" }+            queryMedia(MediaStore.Files.getContentUri("external"), selection, mimes, 2000)+        }+        FileCategory.DOWNLOADS -> emptyList()+    }++    private fun queryRecents(): List<FileBrowserItem> =+        queryMedia(MediaStore.Files.getContentUri("external"), null, null, 40)++    private fun queryMedia(+        uri: Uri,+        selection: String?,+        args: Array<String>?,+        limit: Int,+    ): List<FileBrowserItem> {+        val ctx = getApplication<Application>()+        val projection = arrayOf(MediaStore.MediaColumns.DATA)+        val sort = "${MediaStore.MediaColumns.DATE_MODIFIED} DESC"+        val out = mutableListOf<FileBrowserItem>()+        try {+            ctx.contentResolver.query(uri, projection, selection, args, sort)?.use { c ->+                val idx = c.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)+                while (c.moveToNext() && out.size < limit) {+                    val path = c.getString(idx) ?: continue+                    val f = File(path)+                    if (f.isFile) out.add(f.toItem())+                }+            }+        } catch (_: Exception) {+        }+        return out+    }++    private fun File.toItem() = FileBrowserItem(+        name = name,+        isDirectory = isDirectory,+        size = if (isFile) length() else null,+        realFile = this,+        zipInnerPath = null,+        key = absolutePath,+        lastModified = lastModified(),+    )++    // ---- Clipboard (copy/cut/paste) ----+    private val _clipboard = MutableStateFlow<List<File>>(emptyList())+    val clipboard: StateFlow<List<File>> = _clipboard.asStateFlow()++    private val _clipboardIsCut = MutableStateFlow(false)+    val clipboardIsCut: StateFlow<Boolean> = _clipboardIsCut.asStateFlow()++    override fun copySelection() {+        if (isZipMode()) return+        val files = _selectedPaths.value.mapNotNull { it.realFile }+        if (files.isEmpty()) return+        _clipboard.value = files+        _clipboardIsCut.value = false+        clearSelection()+        emit(getApplication<Application>().getString(R.string.copied_n, files.size))+    }++    override fun cutSelection() {+        if (isZipMode()) return+        val files = _selectedPaths.value.mapNotNull { it.realFile }+        if (files.isEmpty()) return+        _clipboard.value = files+        _clipboardIsCut.value = true+        clearSelection()+        emit(getApplication<Application>().getString(R.string.cut_n, files.size))+    }++    override fun clearClipboard() {+        _clipboard.value = emptyList()+        _clipboardIsCut.value = false+    }++    override fun pasteHere() {+        if (isZipMode()) return+        val sources = _clipboard.value+        if (sources.isEmpty()) return+        val target = _currentDirectory.value+        val isCut = _clipboardIsCut.value+        viewModelScope.launch(Dispatchers.IO) {+            var lastError: Exception? = null+            sources.forEach { source ->+                try {+                    if (!source.exists()) return@forEach+                    // Don't paste a folder into itself or a descendant.+                    if (target.absolutePath == source.absolutePath ||+                        target.absolutePath.startsWith(source.absolutePath + "/")+                    ) return@forEach+                    val dest = uniqueDestination(target, source.name)+                    if (isCut) {+                        source.atomicMoveTo(dest)+                    } else if (source.isDirectory) {+                        source.copyRecursively(dest, overwrite = false)+                    } else {+                        source.copyTo(dest, overwrite = false)+                    }+                } catch (e: Exception) {+                    lastError = e+                }+            }+            if (isCut) clearClipboard()+            loadDirectory()+            lastError?.let { emitMoveFailed(it) }+        }+    }++    override fun shareSelection() {+        val ctx = getApplication<Application>()+        val files = _selectedPaths.value.mapNotNull { it.realFile }.filter { it.isFile }+        if (files.isEmpty()) return+        val uris = ArrayList(files.map {+            FileProvider.getUriForFile(ctx, "${ctx.packageName}.fileprovider", it)+        })+        val intent = if (uris.size == 1) {+            Intent(Intent.ACTION_SEND).apply {+                type = mimeFor(files.first())+                putExtra(Intent.EXTRA_STREAM, uris.first())+            }+        } else {+            Intent(Intent.ACTION_SEND_MULTIPLE).apply {+                type = "*/*"+                putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)+            }+        }.apply { addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK) }+        clearSelection()+        viewModelScope.launch {+            _intents.emit(Intent.createChooser(intent, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+        }+    }++    private fun mimeFor(file: File): String =+        MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension) ?: "*/*"++    /** A destination in [dir] named [name], suffixed with " (n)" if that already exists. */+    private fun uniqueDestination(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+    }+     // ---- Share URIs ----     private val _incomingUris = MutableStateFlow<List<Uri>?>(null)     val incomingUris: StateFlow<List<Uri>?> = _incomingUris.asStateFlow()@@ -128,6 +528,7 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),     init {         loadDirectory()         restartObserver()+        loadHome()     }      fun loadDirectory() {@@ -135,16 +536,34 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),         if (zipFile == null) {             val dir = _currentDirectory.value             viewModelScope.launch(Dispatchers.IO) {-                _entries.value = listRealDir(dir)+                _entries.value = sortEntries(listRealDir(dir))             }         } else {             val inner = _zipInternalPath.value             viewModelScope.launch(Dispatchers.IO) {-                _entries.value = listZipDir(zipFile, inner)+                _entries.value = sortEntries(listZipDir(zipFile, inner))             }         }     } +    private fun sortEntries(+        entries: Pair<List<FileBrowserItem>, List<FileBrowserItem>>+    ): Pair<List<FileBrowserItem>, List<FileBrowserItem>> =+        sortItems(entries.first) to sortItems(entries.second)++    private fun sortItems(items: List<FileBrowserItem>): List<FileBrowserItem> {+        val cmp: Comparator<FileBrowserItem> = when (_sortBy.value) {+            SortBy.NAME -> compareBy { it.name.lowercase() }+            SortBy.DATE -> compareBy { it.lastModified }+            SortBy.SIZE -> compareBy { it.size ?: -1L }+            SortBy.TYPE -> compareBy<FileBrowserItem> {+                it.name.substringAfterLast('.', "").lowercase()+            }.thenBy { it.name.lowercase() }+        }+        val sorted = items.sortedWith(cmp)+        return if (_sortAscending.value) sorted else sorted.reversed()+    }+     private fun restartObserver() {         observerJob?.cancel()         if (isZipMode()) {@@ -166,7 +585,10 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),             _zipPath.value = null             _zipInternalPath.value = ""         }+        _atHome.value = false+        _categoryTitle.value = null         _currentDirectory.value = path+        applyDirDefaults(path)         clearSelection()         loadDirectory()         restartObserver()@@ -198,6 +620,7 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),      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 -> {@@ -215,10 +638,12 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),             }             _currentDirectory.value.absolutePath != rootDirectory.absolutePath -> {                 _currentDirectory.value = _currentDirectory.value.parentFile ?: _currentDirectory.value+                applyDirDefaults(_currentDirectory.value)                 loadDirectory()                 restartObserver()             }-            else -> return false+            // At the storage root, Back returns to the home screen.+            else -> goHome()         }         return true     }@@ -375,17 +800,9 @@ class FilesViewModel(application: Application) : AndroidViewModel(application),     }      private fun listRealDir(dir: File): Pair<List<FileBrowserItem>, List<FileBrowserItem>> {-        val files = dir.listFiles()?.toList() ?: emptyList()-        val items = files.map { f ->-            FileBrowserItem(-                name = f.name,-                isDirectory = f.isDirectory,-                size = if (f.isFile) f.length() else null,-                realFile = f,-                zipInnerPath = null,-                key = f.absolutePath-            )-        }+        val all = dir.listFiles()?.toList() ?: emptyList()+        val visible = if (_showHidden.value) all else all.filterNot { it.name.startsWith(".") }+        val items = visible.map { it.toItem() }         return items.partition { it.isDirectory }     } 
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 acd92e59bd..add14c3db2 100644--- a/files/src/main/res/values/strings.xml+++ b/files/src/main/res/values/strings.xml@@ -41,4 +41,103 @@     <string name="archiving">Archiving…</string>     <!-- Snackbar: incoming shared files saved to current directory successfully -->     <string name="files_saved">Files saved successfully</string>++    <!-- Content description / hint for the search field in the top bar -->+    <string name="search">Search</string>+    <!-- Placeholder shown in the search field -->+    <string name="search_files">Search files…</string>+    <!-- Overflow menu header for choosing sort order. Noun phrase -->+    <string name="sort_by">Sort by</string>+    <!-- Sort option: by file/folder name -->+    <string name="sort_name">Name</string>+    <!-- Sort option: by last-modified date -->+    <string name="sort_date">Date</string>+    <!-- Sort option: by file size -->+    <string name="sort_size">Size</string>+    <!-- Sort option: by file type/extension -->+    <string name="sort_type">Type</string>+    <!-- Menu item toggling ascending/descending order -->+    <string name="reverse_order">Reverse order</string>+    <!-- Sort direction options -->+    <string name="sort_ascending">Ascending</string>+    <string name="sort_descending">Descending</string>+    <!-- Navigation drawer: header + home entry -->+    <string name="menu">Menu</string>+    <string name="home">Home</string>+    <!-- Menu item switching between grid and list layouts -->+    <string name="grid_view">Grid view</string>+    <string name="list_view">List view</string>+    <!-- Menu item selecting every item in the current folder -->+    <string name="select_all">Select all</string>+    <!-- Selection action: copy selected files to the clipboard -->+    <string name="copy">Copy</string>+    <!-- Selection action: cut (move) selected files to the clipboard -->+    <string name="cut">Cut</string>+    <!-- Action: paste clipboard files into the current folder -->+    <string name="paste">Paste</string>+    <!-- Selection action: share selected files -->+    <string name="share">Share</string>+    <!-- Rename dialog title. Verb -->+    <string name="rename">Rename</string>+    <!-- Rename dialog: TextField label for the new name -->+    <string name="new_name_label">New name</string>+    <!-- Snackbar after copying to clipboard. %1$d = item count -->+    <string name="copied_n">Copied <xliff:g id="count" example="3">%1$d</xliff:g> item(s)</string>+    <!-- Snackbar after cutting to clipboard. %1$d = item count -->+    <string name="cut_n">Cut <xliff:g id="count" example="3">%1$d</xliff:g> item(s)</string>+    <!-- Paste bar label. %1$d = number of items on the clipboard -->+    <string name="ready_to_paste"><xliff:g id="count" example="3">%1$d</xliff:g> item(s) ready to paste</string>++    <!-- Snackbar when creating a file/folder fails -->+    <string name="create_failed">Could not create item</string>+    <!-- Snackbar after bookmarking a folder -->+    <string name="bookmark_added">Bookmark added</string>++    <!-- Home screen: category shortcut labels -->+    <string name="cat_images">Images</string>+    <string name="cat_videos">Videos</string>+    <string name="cat_audio">Audio</string>+    <string name="cat_documents">Documents</string>+    <string name="cat_downloads">Downloads</string>++    <!-- Home screen section headers -->+    <string name="internal_storage">Internal storage</string>+    <string name="categories">Categories</string>+    <string name="bookmarks">Bookmarks</string>+    <string name="recent_files">Recent files</string>+    <!-- Storage meter caption. %1$s = used size, %2$s = total size -->+    <string name="storage_usage"><xliff:g id="used" example="12 GB">%1$s</xliff:g> used of <xliff:g id="total" example="128 GB">%2$s</xliff:g></string>++    <!-- Create menu items and dialogs -->+    <string name="new_folder">New folder</string>+    <string name="new_file">New file</string>+    <string name="folder_name_label">Folder name</string>+    <string name="file_name_label">File name</string>+    <string name="create">Create</string>++    <!-- Selection actions -->+    <string name="open_with">Open with</string>+    <string name="properties">Properties</string>+    <string name="add_bookmark">Add bookmark</string>+    <string name="remove_bookmark">Remove bookmark</string>++    <!-- Overflow: show/hide dot-prefixed hidden files -->+    <string name="show_hidden">Show hidden files</string>+    <string name="hide_hidden">Hide hidden files</string>++    <!-- Empty folder placeholder -->+    <string name="no_files">Nothing here</string>++    <!-- Properties dialog rows -->+    <string name="prop_path">Path</string>+    <string name="prop_type">Type</string>+    <string name="prop_size">Size</string>+    <string name="prop_modified">Modified</string>+    <string name="prop_items">Contents</string>+    <string name="type_folder">Folder</string>+    <string name="type_file">File</string>+    <!-- Folder contents count. %1$d = number of items -->+    <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> </resources>