Modern Apps git

← Modern-Apps.git

files: search the whole current root, not just this folder

Commit
34351bb9d6fac9ec779cf9eeabf3e40182935b6a
Author
Vayun Mathur <[email protected]>
When
2026-11-21 02:43 UTC (15 days ago)
Parents
a529379
Files search filtered only the already-loaded directory
listing, so anything in subfolders was unfindable. A BFS walk
from the current browsed root (reusing the browser's own
enumeration; device-wide search deliberately out of scope) now
runs on Dispatchers.IO with 250ms debounce and collectLatest
cancellation, capped at depth 8 and 500 results, tokenized-AND
matching, parent-path subtitles on flattened results, and a
no-results EmptyState for non-blank queries. Zip and category
scopes keep the local filter; a blank query changes nothing.

Verified: :files:testDevUnitTest 120 tests incl. 9 walk tests
(caps, cancellation, symlink escape).

Diff

files/src/main/java/com/vayunmathur/files/platform/FilesBrowseModel.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/FilesBrowseModel.kt b/files/src/main/java/com/vayunmathur/files/platform/FilesBrowseModel.ktindex fd428892b6..106df66ae3 100644--- a/files/src/main/java/com/vayunmathur/files/platform/FilesBrowseModel.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/FilesBrowseModel.kt@@ -3,7 +3,16 @@ package com.vayunmathur.files.platform import android.app.Application import android.os.Environment import androidx.core.content.edit+import androidx.lifecycle.viewModelScope import com.vayunmathur.files.R+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.FlowPreview+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.debounce+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext import java.io.File  /**@@ -71,13 +80,53 @@ abstract class FilesBrowseModel(application: Application) :      override fun setSearchActive(active: Boolean) {         isSearchActiveState.value = active-        if (!active) searchQueryState.value = ""+        if (!active) {+            searchQueryState.value = ""+            searchResultsState.value = emptyList()+            isSearchLoadingState.value = false+        }     }      override fun setSearchQuery(query: String) {         searchQueryState.value = query     } +    /**+     * Recursive search behind [setSearchQuery]: while a non-blank query is+     * active in a real folder, walk that folder (never the whole device, and+     * never inside a zip or a MediaStore category, which keep the old+     * current-listing filter). Debounced, and `collectLatest` cancels the+     * previous walk on Dispatchers.IO as soon as the query or folder changes.+     * Started once from [FilesViewModel]'s init.+     */+    @OptIn(FlowPreview::class)+    fun startSearchPipeline() {+        viewModelScope.launch {+            combine(+                searchQueryState, currentDirectoryState, zipPathState,+                categoryTitleState, showHiddenState,+            ) { query, dir, zip, category, hidden ->+                SearchRequest(query, dir, zip != null, category != null, hidden)+            }.debounce(SEARCH_DEBOUNCE_MS)+                .distinctUntilChanged()+                .collectLatest { request ->+                    if (request.query.isBlank() || request.isVirtual) {+                        searchResultsState.value = emptyList()+                        isSearchLoadingState.value = false+                        return@collectLatest+                    }+                    isSearchLoadingState.value = true+                    try {+                        searchResultsState.value = withContext(Dispatchers.IO) {+                            recursiveSearch(request.root, request.query, request.showHidden)+                        }+                    } finally {+                        isSearchLoadingState.value = false+                    }+                }+        }+    }+     override fun toggleHidden() {         val next = !showHiddenState.value         showHiddenState.value = next@@ -198,3 +247,14 @@ abstract class FilesBrowseModel(application: Application) :         loadTrash()     } }++/** One debounced search-pipeline request; virtual (zip/category) scopes skip the walk. */+private data class SearchRequest(+    val query: String,+    val root: File,+    val inZip: Boolean,+    val inCategory: Boolean,+    val showHidden: Boolean,+) {+    val isVirtual: Boolean get() = inZip || inCategory+}
files/src/main/java/com/vayunmathur/files/platform/FilesCoreModel.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/FilesCoreModel.kt b/files/src/main/java/com/vayunmathur/files/platform/FilesCoreModel.ktindex 85cf267399..2da1e894b0 100644--- a/files/src/main/java/com/vayunmathur/files/platform/FilesCoreModel.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/FilesCoreModel.kt@@ -227,6 +227,14 @@ abstract class FilesCoreModel(application: Application) : AndroidViewModel(appli     internal val isSearchActiveState = MutableStateFlow(false)     val isSearchActive: StateFlow<Boolean> = isSearchActiveState.asStateFlow() +    /** Flattened recursive-search hits for [searchQuery] under the browsed folder. */+    internal val searchResultsState = MutableStateFlow<List<FilesSearchHit>>(emptyList())+    val searchResults: StateFlow<List<FilesSearchHit>> = searchResultsState.asStateFlow()++    /** True while the recursive walk for the current query is still running. */+    internal val isSearchLoadingState = MutableStateFlow(false)+    val isSearchLoading: StateFlow<Boolean> = isSearchLoadingState.asStateFlow()+     internal val showHiddenState = MutableStateFlow(prefs.getBoolean("show_hidden", false))     val showHidden: StateFlow<Boolean> = showHiddenState.asStateFlow() 
files/src/main/java/com/vayunmathur/files/platform/FilesSearch.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/FilesSearch.kt b/files/src/main/java/com/vayunmathur/files/platform/FilesSearch.ktnew file mode 100644index 0000000000..7b68847e45--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/platform/FilesSearch.kt@@ -0,0 +1,116 @@+package com.vayunmathur.files.platform++import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.ensureActive+import java.io.File++/** Debounce applied before a keystroke starts a recursive walk. */+internal const val SEARCH_DEBOUNCE_MS = 250L++/** Deepest level below the search root that is still listed (the root itself is level 0). */+internal const val SEARCH_MAX_DEPTH = 8++/** Hard stop on flattened results, so a huge tree cannot flood the listing. */+internal const val SEARCH_MAX_RESULTS = 500++/** One recursive-search result: the item plus where it lives, for the row subtitle. */+data class FilesSearchHit(+    val item: FileBrowserItem,+    val parentSubtitle: String,+)++/** Splits [query] into lowercase match tokens; blank queries have none (and match all). */+internal fun searchTokens(query: String): List<String> =+    query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() }++/**+ * The listing's name match, tokenized: every whitespace-separated token must be+ * contained in [name] (case-insensitive), so "report pdf" narrows instead of+ * needing the exact phrase. A single token is exactly the old substring match.+ */+internal fun searchMatches(name: String, query: String): Boolean {+    val tokens = searchTokens(query)+    return tokens.isEmpty() || tokens.all { name.contains(it, ignoreCase = true) }+}++/**+ * Where [item] lives under [root], as a row subtitle: the parent folder's path+ * relative to [root] (e.g. "Docs/2024"), or [root]'s own name for items sitting+ * directly in it. Zip entries without a real file derive it from the inner path.+ */+internal fun parentSubtitle(root: File, item: FileBrowserItem): String {+    val real = item.realFile+    if (real != null) {+        val parent = real.parentFile ?: return root.name+        if (parent.absolutePath == root.absolutePath) return root.name.ifEmpty { "/" }+        val relative = runCatching { parent.relativeTo(root).path }.getOrDefault("")+        return relative.ifEmpty { parent.name }+    }+    val inner = item.zipInnerPath ?: return ""+    return inner.substringBeforeLast('/', "")+}++/**+ * Enumerates one directory exactly as the browser does, flattened. This is the+ * only enumeration the walk uses — no new storage backend.+ */+internal fun listDirChildren(dir: File, showHidden: Boolean): List<FileBrowserItem> {+    val (dirs, files) = listRealDirItems(dir, showHidden)+    return dirs + files+}++/**+ * Recursive search under [root] only (the folder the user is browsing — never+ * the whole device). Breadth-first, so shallower hits come first; matching+ * folders are both listed and descended into. Stops descending at+ * [maxDepth] levels, stops collecting at [maxResults], skips directories+ * already visited (symlink cycles), and cooperatively cancels via+ * [ensureActive] between directories, so a superseded query (collectLatest)+ * abandons the walk promptly. Enumeration goes through [listChildren],+ * which defaults to the browser's own [listRealDirItems].+ */+internal suspend fun recursiveSearch(+    root: File,+    query: String,+    showHidden: Boolean = false,+    maxDepth: Int = SEARCH_MAX_DEPTH,+    maxResults: Int = SEARCH_MAX_RESULTS,+    listChildren: (File) -> List<FileBrowserItem> = { listDirChildren(it, showHidden) },+): List<FilesSearchHit> {+    if (searchTokens(query).isEmpty() || maxResults <= 0) return emptyList()+    val hits = mutableListOf<FilesSearchHit>()+    val visited = mutableSetOf<String>()+    val queue = ArrayDeque<Pair<File, Int>>()+    visited += canonicalKey(root)+    queue.addLast(root to 0)+    while (queue.isNotEmpty()) {+        currentCoroutineContext().ensureActive()+        val (dir, depth) = queue.removeFirst()+        if (depth >= maxDepth) continue+        val children = listChildren(dir)+        currentCoroutineContext().ensureActive()+        for (child in children) {+            currentCoroutineContext().ensureActive()+            val childFile = child.realFile ?: continue+            // Scope guard: nothing outside the browsed root is ever reported.+            if (!isWithin(root, childFile)) continue+            if (searchMatches(child.name, query)) {+                hits += FilesSearchHit(child, parentSubtitle(root, child))+                if (hits.size >= maxResults) return hits+            }+            if (child.isDirectory && visited.add(canonicalKey(childFile))) {+                queue.addLast(childFile to depth + 1)+            }+        }+    }+    return hits+}++private fun canonicalKey(file: File): String =+    runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)++private fun isWithin(root: File, file: File): Boolean {+    val rootPath = canonicalKey(root)+    val path = canonicalKey(file)+    return path == rootPath || path.startsWith(rootPath + File.separator)+}
files/src/main/java/com/vayunmathur/files/platform/FilesUiContract.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/FilesUiContract.kt b/files/src/main/java/com/vayunmathur/files/platform/FilesUiContract.ktindex 21c67847b4..dc7293a4ae 100644--- a/files/src/main/java/com/vayunmathur/files/platform/FilesUiContract.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/FilesUiContract.kt@@ -49,6 +49,14 @@ data class FilesUiState(     /** Non-empty while the search field filters the current listing by name. */     val searchQuery: String = "",     val isSearchActive: Boolean = false,+    /**+     * Recursive-search hits under the browsed folder, flattened with parent+     * subtitles. Null means no recursive search supplies this state (previews,+     * zip/category scopes), so the listing keeps its current-folder filter.+     */+    val searchResults: List<FilesSearchHit>? = null,+    /** True while the recursive search walk for [searchQuery] is running. */+    val isSearchLoading: 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. */
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 7bb9243d74..fb9a0438b0 100644--- a/files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/FilesViewModel.kt@@ -46,6 +46,7 @@ class FilesViewModel(application: Application) : FilesTrashModel(application), F         loadDirectory()         restartObserver()         loadHome()+        startSearchPipeline()     }      override fun unzip(zipItem: FileBrowserItem, destPath: File) {
files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.ktindex 57ef843bf7..90bba8d8e5 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryBreadcrumbs.kt@@ -40,6 +40,7 @@ internal fun DirectoryTitle(     actions: FilesActions,     isCategory: Boolean,     isReadOnly: Boolean,+    searchFocusRequester: FocusRequester, ) {     DirectoryTitle(         rootDirectory = state.rootDirectory,@@ -53,6 +54,7 @@ internal fun DirectoryTitle(         actions = actions,         isCategory = isCategory,         isReadOnly = isReadOnly,+        searchFocusRequester = searchFocusRequester,     ) } @@ -69,6 +71,7 @@ internal fun DirectoryTitle(     actions: FilesActions,     isCategory: Boolean,     isReadOnly: Boolean,+    searchFocusRequester: FocusRequester, ) {     val root = rootDirectory     val breadcrumbs = remember(@@ -96,7 +99,6 @@ internal fun DirectoryTitle(     }      if (isSearchActive) {-        val searchFocus = remember { FocusRequester() }         TextField(             value = searchQuery,             onValueChange = { actions.setSearchQuery(it) },@@ -104,9 +106,10 @@ internal fun DirectoryTitle(             singleLine = true,             modifier = Modifier                 .fillMaxWidth()-                .focusRequester(searchFocus),+                .focusRequester(searchFocusRequester),         )-        LaunchedEffect(Unit) { searchFocus.requestFocus() }+        // Autofocus on activation; Ctrl+F/L re-requests via the hoisted requester.+        LaunchedEffect(Unit) { searchFocusRequester.requestFocus() }     } else if (isCategory) {         Text(categoryTitle.orEmpty(), style = MaterialTheme.typography.titleLarge)     } else {
files/src/main/java/com/vayunmathur/files/ui/DirectoryKeys.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryKeys.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryKeys.ktnew file mode 100644index 0000000000..7b0d0621bd--- /dev/null+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryKeys.kt@@ -0,0 +1,62 @@+package com.vayunmathur.files.ui++import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEvent+import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.isCtrlPressed+import androidx.compose.ui.input.key.isMetaPressed+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.type++/**+ * Desktop keyboard shortcuts for the directory browser, following the `code`+ * editor's key-handler pattern: only key-down events, Ctrl or Meta as the+ * shortcut modifier (Cmd on macOS-style keyboards), and never while a dialog+ * is open — a modal owns its keys.+ *+ * Escape unwinds one layer at a time, in the same order as Back: an active+ * search is cleared first (deactivating search also clears its query), then+ * any selection. Ctrl+A is deliberately not consumed while search is active:+ * the focused search field keeps its own select-all-the-query behaviour.+ */+internal fun handleDirectoryKey(+    event: KeyEvent,+    dialogOpen: Boolean,+    isSearchActive: Boolean,+    hasSelection: Boolean,+    onFocusSearch: () -> Unit,+    onSelectAll: () -> Unit,+    onClearSearch: () -> Unit,+    onClearSelection: () -> Unit,+): Boolean {+    if (event.type != KeyEventType.KeyDown || dialogOpen) return false+    if (event.key == Key.Escape) {+        return when {+            isSearchActive -> {+                onClearSearch()+                true+            }+            hasSelection -> {+                onClearSelection()+                true+            }+            else -> false+        }+    }+    if (!event.isCtrlPressed && !event.isMetaPressed) return false+    return when (event.key) {+        Key.F, Key.L -> {+            onFocusSearch()+            true+        }+        Key.A -> {+            if (isSearchActive) {+                false+            } else {+                onSelectAll()+                true+            }+        }+        else -> false+    }+}
files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt b/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.ktindex 3d0a16f226..642f17c164 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryListing.kt@@ -18,11 +18,14 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.files.R import com.vayunmathur.files.platform.FileBrowserItem import com.vayunmathur.files.platform.FilesActions+import com.vayunmathur.files.platform.FilesSearchHit import com.vayunmathur.files.platform.FilesUiState import com.vayunmathur.files.platform.ViewMode+import com.vayunmathur.files.platform.searchMatches import com.vayunmathur.files.ui.components.DirectoryItem import com.vayunmathur.files.ui.components.GridItem import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconClose@@ -52,6 +55,8 @@ internal fun DirectoryListing(         directories = state.directories,         files = state.files,         searchQuery = state.searchQuery,+        searchResults = state.searchResults,+        isSearchLoading = state.isSearchLoading,         clipboardCount = state.clipboardCount,         selectedPaths = state.selectedPaths,         isSearchActive = state.isSearchActive,@@ -79,11 +84,27 @@ internal fun DirectoryListing(     modifier: Modifier = Modifier,     /** Clears the rename dialog target; owned by [DirectoryScreen]. */     onClearRenameTarget: () -> Unit = {},+    /**+     * Recursive-search hits for a non-blank query, flattened with parent+     * subtitles. Null keeps the current-folder fast path/filter (blank query,+     * previews, zip and category scopes).+     */+    searchResults: List<FilesSearchHit>? = null,+    /** True while the recursive walk for [searchQuery] is still running. */+    isSearchLoading: Boolean = false, ) {     val query = searchQuery.trim()-    fun matches(item: FileBrowserItem) =-        query.isEmpty() || item.name.contains(query, ignoreCase = true)-    val allItems = (directories + files).filter(::matches)+    val useRecursive = query.isNotEmpty() && searchResults != null+    val subtitles = if (useRecursive) {+        searchResults.associate { it.item.key to it.parentSubtitle }+    } else {+        emptyMap()+    }+    val allItems = if (useRecursive) {+        searchResults.map { it.item }+    } else {+        (directories + files).filter { searchMatches(it.name, query) }+    }      Column(modifier) {             // Paste bar: shown when the clipboard has files and we can write here.@@ -126,9 +147,18 @@ internal fun DirectoryListing(                 }             } -            if (allItems.isEmpty()) {+            if (useRecursive && isSearchLoading && allItems.isEmpty()) {+                LoadingState(+                    message = stringResource(R.string.searching_files),+                    modifier = Modifier.weight(1f).fillMaxWidth(),+                )+            } else if (allItems.isEmpty()) {                 EmptyState(-                    title = stringResource(R.string.no_files),+                    title = if (query.isNotEmpty()) {+                        stringResource(R.string.no_search_results, query)+                    } else {+                        stringResource(R.string.no_files)+                    },                     modifier = Modifier.weight(1f).fillMaxWidth(),                 )             } else if (viewMode == ViewMode.GRID) {@@ -142,6 +172,7 @@ internal fun DirectoryListing(                             isSelected = selectedPaths.any { it.key == child.key },                             onClick = { onItemClick(child) },                             onLongClick = { onItemLongClick(child) },+                            subtitle = subtitles[child.key],                         )                     }                 }@@ -153,6 +184,7 @@ internal fun DirectoryListing(                             file = child,                             isSelected = isSelected,                             isReadOnly = isReadOnly,+                            subtitle = subtitles[child.key],                             onLongClick = { onItemLongClick(child) },                             onClick = { onItemClick(child) },                             onMove = { sources: List<File> ->
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 4eaac99406..9f284a24f8 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryPage.kt@@ -102,7 +102,7 @@ fun DirectoryPage(         actions = actions,         snackbarHostState = snackbarHostState,         onOpenDrawer = onOpenDrawer,-        title = { DirectoryTitleLive(viewModel, actions, isCurrent) },+        title = { searchFocus -> DirectoryTitleLive(viewModel, actions, isCurrent, searchFocus) },         topActions = { onRename, onShowProperties, onArchive, onShowNewFolder, onShowNewFile ->             DirectoryTopActionsLive(                 viewModel = viewModel,@@ -138,6 +138,7 @@ private fun DirectoryTitleLive(     viewModel: FilesViewModel,     actions: FilesActions,     isCurrent: Boolean,+    searchFocusRequester: androidx.compose.ui.focus.FocusRequester, ) {     val currentDirectory by viewModel.currentDirectory.collectAsStateWithLifecycle()     val zipPath by viewModel.zipPath.collectAsStateWithLifecycle()@@ -159,6 +160,7 @@ private fun DirectoryTitleLive(         actions = actions,         isCategory = shownCategoryTitle != null,         isReadOnly = shownZipPath != null,+        searchFocusRequester = searchFocusRequester,     ) } @@ -278,16 +280,27 @@ private fun DirectoryListingLive(     onClearRenameTarget: () -> Unit, ) {     val entries by viewModel.entries.collectAsStateWithLifecycle()+    val categoryTitle by viewModel.categoryTitle.collectAsStateWithLifecycle()     val searchQuery by viewModel.searchQuery.collectAsStateWithLifecycle()+    val searchResults by viewModel.searchResults.collectAsStateWithLifecycle()+    val isSearchLoading by viewModel.isSearchLoading.collectAsStateWithLifecycle()     val clipboard by viewModel.clipboard.collectAsStateWithLifecycle()     val selectedPaths by viewModel.selectedPaths.collectAsStateWithLifecycle()     val isSearchActive by viewModel.isSearchActive.collectAsStateWithLifecycle()     val viewMode by viewModel.viewMode.collectAsStateWithLifecycle()     val (directories, files) = frozen(isCurrent, entries)+    // Zip and category scopes keep the current-listing filter: no recursive walk.+    val recursiveResults = if (isReadOnly || frozen(isCurrent, categoryTitle) != null) {+        null+    } else {+        frozen(isCurrent, searchResults)+    }     DirectoryListing(         directories = directories,         files = files,         searchQuery = frozen(isCurrent, searchQuery),+        searchResults = recursiveResults,+        isSearchLoading = frozen(isCurrent, isSearchLoading),         clipboardCount = frozen(isCurrent, clipboard).size,         selectedPaths = frozen(isCurrent, selectedPaths),         isSearchActive = frozen(isCurrent, isSearchActive),
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 4b82782fd8..4d9130e262 100644--- a/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/DirectoryScreen.kt@@ -17,6 +17,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction@@ -67,12 +68,13 @@ fun DirectoryScreen(         actions = actions,         snackbarHostState = snackbarHostState,         onOpenDrawer = onOpenDrawer,-        title = {+        title = { searchFocusRequester ->             DirectoryTitle(                 state = state,                 actions = actions,                 isCategory = isCategory,                 isReadOnly = isReadOnly,+                searchFocusRequester = searchFocusRequester,             )         },         topActions = { onRename, onShowProperties, onArchive, onShowNewFolder, onShowNewFile ->@@ -182,7 +184,7 @@ internal fun DirectoryScreenCore(     actions: FilesActions,     snackbarHostState: SnackbarHostState,     onOpenDrawer: () -> Unit,-    title: @Composable () -> Unit,+    title: @Composable (androidx.compose.ui.focus.FocusRequester) -> Unit,     topActions: @Composable (         onRename: (FileBrowserItem) -> Unit,         onShowProperties: (FileBrowserItem) -> Unit,@@ -285,6 +287,11 @@ internal fun DirectoryScreenCore(     }      val focusManager = LocalFocusManager.current+    // Hoisted so the desktop shortcut handler below can (re)focus the search+    // field in DirectoryTitle; activating search also autofocuses it there.+    val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }+    val anyDialogOpen = showArchiveDialog || itemBeingRenamed != null ||+        showNewFolderDialog || showNewFileDialog || itemForProperties != null      // 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@@ -296,6 +303,21 @@ internal fun DirectoryScreenCore(      AppScaffold(         modifier = Modifier+            .onPreviewKeyEvent { event ->+                handleDirectoryKey(+                    event = event,+                    dialogOpen = anyDialogOpen,+                    isSearchActive = isSearchActive,+                    hasSelection = selectedPaths.isNotEmpty(),+                    onFocusSearch = {+                        if (isSearchActive) searchFocusRequester.requestFocus()+                        else actions.setSearchActive(true)+                    },+                    onSelectAll = { actions.selectAll() },+                    onClearSearch = { actions.setSearchActive(false) },+                    onClearSelection = { actions.clearSelection() },+                )+            }             .clickable(                 interactionSource = remember { MutableInteractionSource() }, indication = null             ) {@@ -309,7 +331,7 @@ internal fun DirectoryScreenCore(                     IconButton(onClick = onOpenDrawer) { IconMenu() }                 }             },-        title = title,+        title = { title(searchFocusRequester) },         actions = {             topActions(                 { itemBeingRenamed = it },
files/src/main/java/com/vayunmathur/files/ui/components/DirectoryItem.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/components/DirectoryItem.kt b/files/src/main/java/com/vayunmathur/files/ui/components/DirectoryItem.ktindex 27cb69c2ff..2831e41c02 100644--- a/files/src/main/java/com/vayunmathur/files/ui/components/DirectoryItem.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/components/DirectoryItem.kt@@ -43,7 +43,9 @@ fun DirectoryItem(     onLongClick: () -> Unit,     onClick: () -> Unit,     onMove: (List<File>) -> Unit,-    onStartDrag: () -> List<File>+    onStartDrag: () -> List<File>,+    /** Parent-path subtitle for recursive-search hits; null in normal browsing. */+    subtitle: String? = null, ) {     var isDraggingOver by remember { mutableStateOf(false) }     val currentOnMove by rememberUpdatedState(onMove)@@ -123,7 +125,9 @@ fun DirectoryItem(             content = { Text(file.name.ifEmpty { "/" }) },             leadingContent = { FileLeading(file, isSelected, 40.dp) },             supportingContent = {-                if (!file.isDirectory) {+                if (subtitle != null) {+                    Text(subtitle)+                } else if (!file.isDirectory) {                     file.size?.let { size -> Text(Formatter.formatShortFileSize(context, size)) }                 }             },
files/src/main/java/com/vayunmathur/files/ui/components/GridItem.kt
diff --git a/files/src/main/java/com/vayunmathur/files/ui/components/GridItem.kt b/files/src/main/java/com/vayunmathur/files/ui/components/GridItem.ktindex 0d1f142a93..acb9e97600 100644--- a/files/src/main/java/com/vayunmathur/files/ui/components/GridItem.kt+++ b/files/src/main/java/com/vayunmathur/files/ui/components/GridItem.kt@@ -28,6 +28,8 @@ fun GridItem(     isSelected: Boolean,     onClick: () -> Unit,     onLongClick: () -> Unit,+    /** Parent-path subtitle for recursive-search hits; null in normal browsing. */+    subtitle: String? = null, ) {     Column(         modifier = Modifier@@ -50,5 +52,15 @@ fun GridItem(             overflow = TextOverflow.Ellipsis,             textAlign = TextAlign.Center,         )+        if (subtitle != null) {+            Text(+                text = subtitle,+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.outline,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+                textAlign = TextAlign.Center,+            )+        }     } }
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 2d396edd56..1462b6b029 100644--- a/files/src/main/res/values/strings.xml+++ b/files/src/main/res/values/strings.xml@@ -119,6 +119,10 @@      <!-- Empty folder placeholder -->     <string name="no_files">Nothing here</string>+    <!-- Search: no recursive results for the query. %1$s = query -->+    <string name="no_search_results">No results for “%1$s”</string>+    <!-- Search: recursive walk in progress -->+    <string name="searching_files">Searching…</string>      <!-- Properties dialog rows -->     <string name="prop_path">Path</string>
files/src/test/java/com/vayunmathur/files/platform/FilesSearchTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/platform/FilesSearchTest.kt b/files/src/test/java/com/vayunmathur/files/platform/FilesSearchTest.ktnew file mode 100644index 0000000000..aaca6325ad--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/platform/FilesSearchTest.kt@@ -0,0 +1,170 @@+package com.vayunmathur.files.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Deferred+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class FilesSearchTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun tempDir(name: String): File =+        File(ctx.cacheDir, "search-$name-${System.nanoTime()}").apply { mkdirs() }++    private fun File.file(name: String): File = File(this, name).apply { writeText("x") }+    private fun File.dir(name: String): File = File(this, name).apply { mkdirs() }++    @Test+    fun `tokenized match is AND case-insensitive and blank matches all`() {+        assertTrue(searchMatches("Annual Report.PDF", "report pdf"))+        assertTrue(searchMatches("Annual Report.PDF", "REPORT"))+        assertTrue(searchMatches("anything.txt", ""))+        assertTrue(searchMatches("anything.txt", "   "))+        assertFalse(searchMatches("Annual Report.PDF", "report xls"))+        assertFalse(searchMatches("notes.txt", "report"))+        assertEquals(listOf("report", "pdf"), searchTokens("  Report   PDF "))+        assertEquals(emptyList(), searchTokens("  "))+    }++    @Test+    fun `recursive search finds nested hits and matching folders`() = runBlocking<Unit> {+        val root = tempDir("nested")+        root.file("top-report.txt")+        val docs = root.dir("Docs")+        docs.file("report-2024.txt")+        docs.file("other.txt")+        val deep = docs.dir("inner")+        deep.file("deep report.txt")+        val hits = recursiveSearch(root, "report")+        assertEquals(+            setOf("top-report.txt", "report-2024.txt", "deep report.txt"),+            hits.map { it.item.name }.toSet(),+        )+        // Shallower hits come first (breadth-first).+        assertEquals("top-report.txt", hits.first().item.name)+        // The root itself is never a hit, and non-matches stay out.+        assertTrue(hits.none { it.item.realFile == root })+        root.deleteRecursively()+    }++    @Test+    fun `depth cap stops descent at the limit`() = runBlocking<Unit> {+        val root = tempDir("depth")+        var current = root+        // level1/target.txt at depth 2 ... levelN/target.txt at depth N+1+        repeat(10) { level ->+            current = current.dir("level${level + 1}")+            current.file("target.txt")+        }+        val capped = recursiveSearch(root, "target", maxDepth = 2)+        assertEquals(listOf("target.txt"), capped.map { it.item.name })+        assertEquals("level1", capped.single().parentSubtitle)++        val defaultDepth = recursiveSearch(root, "target")+        // Files at depths 2..8 are in, depths 9..11 are out.+        assertEquals(7, defaultDepth.size)+        assertEquals(8, SEARCH_MAX_DEPTH)+        root.deleteRecursively()+    }++    @Test+    fun `result cap truncates the flattened hits`() = runBlocking<Unit> {+        val root = tempDir("cap")+        repeat(10) { root.file("match-$it.txt") }+        val hits = recursiveSearch(root, "match", maxResults = 3)+        assertEquals(3, hits.size)+        assertEquals(500, SEARCH_MAX_RESULTS)+        root.deleteRecursively()+    }++    @Test+    fun `blank query and non-directory root search nothing`() = runBlocking<Unit> {+        val root = tempDir("blank")+        root.file("a.txt")+        assertTrue(recursiveSearch(root, "  ").isEmpty())+        assertTrue(recursiveSearch(File(root, "a.txt"), "a").isEmpty())+        root.deleteRecursively()+    }++    @Test+    fun `hidden folders are skipped unless showHidden`() = runBlocking<Unit> {+        val root = tempDir("hidden")+        val hidden = root.dir(".secret")+        hidden.file("report.txt")+        assertTrue(recursiveSearch(root, "report", showHidden = false).isEmpty())+        assertEquals(1, recursiveSearch(root, "report", showHidden = true).size)+        root.deleteRecursively()+    }++    @Test+    fun `cancellation abandons the walk`() = runBlocking<Unit> {+        val root = tempDir("cancel")+        val sub = root.dir("sub")+        sub.file("target.txt")+        root.dir("later").file("target.txt")+        lateinit var deferred: Deferred<List<FilesSearchHit>>+        deferred = async {+            recursiveSearch(root, "target", listChildren = { dir ->+                if (dir == sub) deferred.cancel()+                listDirChildren(dir, showHidden = false)+            })+        }+        assertFailsWith<CancellationException> { deferred.await() }+        assertTrue(deferred.isCancelled)+        root.deleteRecursively()+    }++    @Test+    fun `parent subtitle is the path relative to the search root`() = runBlocking<Unit> {+        val root = tempDir("subtitle")+        val docs = root.dir("Docs")+        val year = docs.dir("2024")+        val nested = year.file("report.txt")+        val direct = root.file("report.txt")+        assertEquals("Docs/2024", parentSubtitle(root, nested.toBrowserItem()))+        assertEquals(root.name, parentSubtitle(root, direct.toBrowserItem()))+        val hits = recursiveSearch(root, "report")+        assertEquals(+            mapOf("Docs/2024" to 1, root.name to 1),+            hits.groupingBy { it.parentSubtitle }.eachCount(),+        )+        // Zip entries derive the subtitle from the inner path instead.+        val zipItem = FileBrowserItem(+            name = "z.txt", isDirectory = false, size = 1,+            realFile = null, zipInnerPath = "docs/inner/z.txt", key = "zip:docs/inner/z.txt",+        )+        assertEquals("docs/inner", parentSubtitle(root, zipItem))+        val zipTop = zipItem.copy(zipInnerPath = "z.txt", key = "zip:z.txt")+        assertEquals("", parentSubtitle(root, zipTop))+        root.deleteRecursively()+    }++    @Test+    fun `symlink escaping the root is not followed`() = runBlocking<Unit> {+        val root = tempDir("scope")+        val outside = tempDir("outside")+        outside.file("escaped-target.txt")+        val link = File(root, "link")+        val created = runCatching {+            java.nio.file.Files.createSymbolicLink(link.toPath(), outside.toPath())+        }.isSuccess+        if (created) {+            val hits = recursiveSearch(root, "target")+            assertTrue(hits.isEmpty(), "outside-root symlink must not be searched: $hits")+        }+        root.deleteRecursively()+        outside.deleteRecursively()+    }+}
files/src/test/java/com/vayunmathur/files/ui/DirectoryKeysTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/DirectoryKeysTest.kt b/files/src/test/java/com/vayunmathur/files/ui/DirectoryKeysTest.ktnew file mode 100644index 0000000000..6befab55bd--- /dev/null+++ b/files/src/test/java/com/vayunmathur/files/ui/DirectoryKeysTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.files.ui++import android.view.KeyEvent as AndroidKeyEvent+import androidx.compose.ui.input.key.KeyEvent+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Direct tests for [handleDirectoryKey]: focus-search, select-all and Escape ordering. */+@RunWith(RobolectricTestRunner::class)+class DirectoryKeysTest {++    private class Sink {+        val calls = mutableListOf<String>()+    }++    private fun event(keyCode: Int, meta: Int = 0, action: Int = AndroidKeyEvent.ACTION_DOWN): KeyEvent =+        KeyEvent(AndroidKeyEvent(0L, 0L, action, keyCode, 0, meta))++    private fun handle(+        e: KeyEvent,+        dialogOpen: Boolean = false,+        isSearchActive: Boolean = false,+        hasSelection: Boolean = false,+        sink: Sink = Sink(),+    ): Pair<Boolean, Sink> {+        val handled = handleDirectoryKey(+            event = e,+            dialogOpen = dialogOpen,+            isSearchActive = isSearchActive,+            hasSelection = hasSelection,+            onFocusSearch = { sink.calls += "focusSearch" },+            onSelectAll = { sink.calls += "selectAll" },+            onClearSearch = { sink.calls += "clearSearch" },+            onClearSelection = { sink.calls += "clearSelection" },+        )+        return handled to sink+    }++    private val ctrl = AndroidKeyEvent.META_CTRL_ON+    private val metaKey = AndroidKeyEvent.META_META_ON++    @Test+    fun ctrlAndMetaFocusSearch() {+        assertEquals(listOf("focusSearch"), handle(event(AndroidKeyEvent.KEYCODE_F, ctrl)).second.calls)+        assertEquals(listOf("focusSearch"), handle(event(AndroidKeyEvent.KEYCODE_L, ctrl)).second.calls)+        assertEquals(listOf("focusSearch"), handle(event(AndroidKeyEvent.KEYCODE_F, metaKey)).second.calls)+    }++    @Test+    fun ctrlASelectsAllOnlyOutsideSearch() {+        assertTrue(handle(event(AndroidKeyEvent.KEYCODE_A, ctrl)).first)+        assertEquals(listOf("selectAll"), handle(event(AndroidKeyEvent.KEYCODE_A, ctrl)).second.calls)+        // Inside the search field, Ctrl+A keeps selecting the query text.+        val (handled, sink) = handle(event(AndroidKeyEvent.KEYCODE_A, ctrl), isSearchActive = true)+        assertFalse(handled)+        assertEquals(emptyList(), sink.calls)+    }++    @Test+    fun escapeClearsSearchBeforeSelection() {+        val (_, s1) = handle(+            event(AndroidKeyEvent.KEYCODE_ESCAPE), isSearchActive = true, hasSelection = true)+        assertEquals(listOf("clearSearch"), s1.calls)+        val (_, s2) = handle(event(AndroidKeyEvent.KEYCODE_ESCAPE), hasSelection = true)+        assertEquals(listOf("clearSelection"), s2.calls)+        assertFalse(handle(event(AndroidKeyEvent.KEYCODE_ESCAPE)).first)+    }++    @Test+    fun dialogOpenPlainUnknownAndKeyUpAreNotHandled() {+        assertFalse(handle(event(AndroidKeyEvent.KEYCODE_F, ctrl), dialogOpen = true).first)+        assertFalse(handle(event(AndroidKeyEvent.KEYCODE_ESCAPE), dialogOpen = true).first)+        assertFalse(handle(event(AndroidKeyEvent.KEYCODE_F)).first)+        assertFalse(handle(event(AndroidKeyEvent.KEYCODE_X, ctrl)).first)+        assertFalse(handle(event(AndroidKeyEvent.KEYCODE_F, ctrl, AndroidKeyEvent.ACTION_UP)).first)+    }+}
files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt
diff --git a/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt b/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.ktindex 783dbdbab0..0a7280b585 100644--- a/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt+++ b/files/src/test/java/com/vayunmathur/files/ui/DirectoryScreenTest.kt@@ -359,6 +359,43 @@ class DirectoryScreenTest {         rule.waitForIdle()     } +    @Test+    fun `recursive search results render flattened with parent subtitles`() {+        val actions = RecordingFilesActions()+        val hit = com.vayunmathur.files.platform.FilesSearchHit(+            fileItem("deep-report.txt", File(root, "Docs/inner")),+            parentSubtitle = "Docs/inner",+        )+        rule.setContent {+            DirectoryScreen(+                state = baseState().copy(+                    isSearchActive = true, searchQuery = "report",+                    searchResults = listOf(hit),+                ),+                actions = actions,+            )+        }+        rule.onNodeWithText("deep-report.txt").assertIsDisplayed()+        rule.onNodeWithText("Docs/inner").assertIsDisplayed()+        // Current-folder items that do not come from the walk are not shown.+        rule.onNodeWithText("notes.txt").assertDoesNotExist()+    }++    @Test+    fun `recursive search with no hits shows the no-results state`() {+        val actions = RecordingFilesActions()+        rule.setContent {+            DirectoryScreen(+                state = baseState().copy(+                    isSearchActive = true, searchQuery = "zzznothing",+                    searchResults = emptyList(),+                ),+                actions = actions,+            )+        }+        rule.onNodeWithText("No results for", substring = true).assertIsDisplayed()+    }+     @Test     fun `sort labels cover every sort`() {         rule.setContent {