Modern Apps git

← Modern-Apps.git

code: add command palette, fuzzy quick-open and recent files

Commit
7e1e9b98adcc3d26843f712bb2772f9301ad82ed
Author
vayun-mathur <[email protected]>
When
2026-08-06 23:34 UTC (4 months ago)
Parents
6ad021a

Diff

code/src/main/java/com/vayunmathur/code/ui/CommandPalette.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CommandPalette.kt b/code/src/main/java/com/vayunmathur/code/ui/CommandPalette.ktnew file mode 100644index 0000000000..37a6768ada--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/CommandPalette.kt@@ -0,0 +1,133 @@+package com.vayunmathur.code.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.code.R+import com.vayunmathur.code.util.CodeUiState+import com.vayunmathur.code.util.fuzzyRank+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * One selectable row in the fuzzy picker. [matchKey] is what the query is scored against (the file+ * path for quick-open, the command title for the palette); [primary]/[secondary] are what is drawn.+ */+data class PickerItem(+    val primary: String,+    val secondary: String? = null,+    val matchKey: String = primary,+    val onSelect: () -> Unit,+)++private const val MAX_PICKER_RESULTS = 50++/**+ * A keyboard-first fuzzy picker used by both quick-open and the command palette: a text field over+ * a filtered, ranked list. Selecting a row runs its action and dismisses. When the query is blank+ * [emptyQueryItems] is shown as-is (quick-open uses it for recent files).+ */+@Composable+fun FuzzyPickerDialog(+    title: String,+    placeholder: String,+    items: List<PickerItem>,+    onDismiss: () -> Unit,+    emptyQueryItems: List<PickerItem> = items,+) {+    var query by remember { mutableStateOf("") }+    val filtered = remember(query, items, emptyQueryItems) {+        if (query.isBlank()) emptyQueryItems else fuzzyRank(query, items) { it.matchKey }+    }+    val focusRequester = remember { FocusRequester() }++    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(title) },+        text = {+            Column(Modifier.fillMaxWidth()) {+                OutlinedTextField(+                    value = query,+                    onValueChange = { query = it },+                    singleLine = true,+                    label = { Text(placeholder) },+                    modifier = Modifier.fillMaxWidth().focusRequester(focusRequester),+                )+                Spacer(Modifier.padding(4.dp))+                LazyColumn(Modifier.fillMaxWidth().heightIn(max = 320.dp)) {+                    if (filtered.isEmpty()) {+                        item {+                            Text(+                                stringResource(R.string.no_results),+                                color = MaterialTheme.colorScheme.onSurfaceVariant,+                                modifier = Modifier.padding(vertical = 8.dp),+                            )+                        }+                    }+                    items(filtered.take(MAX_PICKER_RESULTS)) { row ->+                        Column(+                            Modifier+                                .fillMaxWidth()+                                .clickable { row.onSelect(); onDismiss() }+                                .padding(vertical = 8.dp),+                        ) {+                            Text(+                                row.primary,+                                maxLines = 1,+                                overflow = TextOverflow.Ellipsis,+                                color = MaterialTheme.colorScheme.onSurface,+                            )+                            row.secondary?.let {+                                Text(+                                    it,+                                    style = MaterialTheme.typography.labelSmall,+                                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                                    maxLines = 1,+                                    overflow = TextOverflow.Ellipsis,+                                )+                            }+                        }+                    }+                }+            }+        },+        confirmButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.close)) }+        },+    )++    // Focus the field on open so the keyboard is ready to type immediately.+    LaunchedEffect(Unit) { runCatching { focusRequester.requestFocus() } }+}++/** Quick-open rows: every project file, each opening its path when chosen. */+fun quickOpenItems(state: CodeUiState, onOpenPath: (String) -> Unit): List<PickerItem> =+    state.projectFiles.map { file ->+        PickerItem(file.name, file.relativePath, file.relativePath) { onOpenPath(file.path) }+    }++/** Recent-file rows shown by quick-open when the query is empty. */+fun recentOpenItems(state: CodeUiState, onOpenPath: (String) -> Unit): List<PickerItem> =+    state.recentFiles.map { file ->+        PickerItem(file.name, file.relativePath, file.relativePath) { onOpenPath(file.path) }+    }
code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.ktindex 79737b771b..0e67d95fdb 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -29,6 +29,13 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.isCtrlPressed+import androidx.compose.ui.input.key.isShiftPressed+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.input.key.type import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.code.util.CodeActions@@ -48,6 +55,7 @@ import com.vayunmathur.library.ui.IconMenu import com.vayunmathur.library.ui.IconMoreVert import com.vayunmathur.library.ui.IconRedo import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconUndo import com.vayunmathur.library.ui.IconWrapText@@ -128,7 +136,31 @@ fun EditorScreen(     )     val scope = rememberCoroutineScope()     var showFind by remember { mutableStateOf(initialFind != null) }+    var showGoToLine by remember { mutableStateOf(false) }+    var showQuickOpen by remember { mutableStateOf(false) }+    var showPalette by remember { mutableStateOf(false) } +    Box(+        Modifier+            .fillMaxSize()+            .onPreviewKeyEvent { event ->+                if (event.type != KeyEventType.KeyDown || !event.isCtrlPressed) {+                    return@onPreviewKeyEvent false+                }+                when (event.key) {+                    Key.P -> {+                        if (event.isShiftPressed) {+                            showPalette = true+                        } else {+                            actions.refreshProjectFiles()+                            showQuickOpen = true+                        }+                        true+                    }+                    else -> false+                }+            },+    ) {     ModalNavigationDrawer(         drawerState = drawerState,         drawerContent = {@@ -151,6 +183,10 @@ fun EditorScreen(                         IconButton(onClick = { scope.launch { drawerState.open() } }) { IconMenu() }                     },                     actions = {+                        IconButton(onClick = {+                            actions.refreshProjectFiles()+                            showQuickOpen = true+                        }) { IconSearch() }                         IconButton(onClick = onOpenSettings) { IconSettings() }                     },                 )@@ -167,10 +203,16 @@ fun EditorScreen(                         state = state,                         actions = actions,                         onToggleFind = { showFind = !showFind },+                        onGoToLine = { showGoToLine = true },                         onOpenSearch = onOpenSearch,                         onOpenGit = onOpenGit,                         onOpenTerminal = onOpenTerminal,                         onOpenPreview = onOpenPreview,+                        onOpenQuickOpen = {+                            actions.refreshProjectFiles()+                            showQuickOpen = true+                        },+                        onOpenPalette = { showPalette = true },                     )                     HorizontalDivider()                     CodeEditor(@@ -190,6 +232,46 @@ fun EditorScreen(             }         }     }++    if (showQuickOpen) {+        FuzzyPickerDialog(+            title = stringResource(R.string.quick_open),+            placeholder = stringResource(R.string.quick_open_hint),+            items = quickOpenItems(state) { actions.openPath(it) },+            emptyQueryItems = recentOpenItems(state) { actions.openPath(it) },+            onDismiss = { showQuickOpen = false },+        )+    }+    if (showPalette) {+        FuzzyPickerDialog(+            title = stringResource(R.string.command_palette),+            placeholder = stringResource(R.string.command_palette_hint),+            items = editorCommands(+                actions = actions,+                onToggleFind = { showFind = true },+                onGoToLine = { showGoToLine = true },+                onQuickOpen = {+                    actions.refreshProjectFiles()+                    showQuickOpen = true+                },+                onOpenSearch = onOpenSearch,+                onOpenGit = onOpenGit,+                onOpenTerminal = onOpenTerminal,+                onOpenPreview = onOpenPreview,+                onOpenSettings = onOpenSettings,+                onOpenFolder = onOpenFolder,+                onOpenFile = onOpenFile,+            ),+            onDismiss = { showPalette = false },+        )+    }+    if (showGoToLine) {+        GoToLineDialog(+            onGo = { actions.goToLine(it) },+            onDismiss = { showGoToLine = false },+        )+    }+    } }  /** Shown when nothing is open: prompts the user to open a folder or a single file. */@@ -278,13 +360,15 @@ private fun EditorToolbar(     state: CodeUiState,     actions: CodeActions,     onToggleFind: () -> Unit,+    onGoToLine: () -> Unit = {},     onOpenSearch: () -> Unit = {},     onOpenGit: () -> Unit = {},     onOpenTerminal: () -> Unit = {},     onOpenPreview: () -> Unit = {},+    onOpenQuickOpen: () -> Unit = {},+    onOpenPalette: () -> Unit = {}, ) {     val tab = state.currentTab ?: return-    var showGoToLine by remember { mutableStateOf(false) }     Row(         modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),         verticalAlignment = Alignment.CenterVertically,@@ -301,7 +385,9 @@ private fun EditorToolbar(         }         IconButton(onClick = { actions.insertText(" ".repeat(state.tabWidth)) }) { IconFormatIndentIncrease() }         OverflowMenu(icon = { IconMoreVert() }) {-            Item(text = stringResource(R.string.go_to_line)) { showGoToLine = true }+            Item(text = stringResource(R.string.command_palette)) { onOpenPalette() }+            Item(text = stringResource(R.string.quick_open)) { onOpenQuickOpen() }+            Item(text = stringResource(R.string.go_to_line)) { onGoToLine() }             Item(text = stringResource(R.string.toggle_comment)) { actions.toggleComment() }             Item(text = stringResource(R.string.duplicate_line)) { actions.duplicateLine() }             Item(text = stringResource(R.string.move_line_up)) { actions.moveLineUp() }@@ -321,13 +407,6 @@ private fun EditorToolbar(             modifier = Modifier.padding(horizontal = 12.dp),         )     }--    if (showGoToLine) {-        GoToLineDialog(-            onGo = { actions.goToLine(it) },-            onDismiss = { showGoToLine = false },-        )-    } }  /** A small dialog that reads a line number and jumps the caret to it. */@@ -357,3 +436,40 @@ private fun GoToLineDialog(onGo: (Int) -> Unit, onDismiss: () -> Unit) {         },     ) }++/** The command-palette registry: named actions mapped to editor callbacks and nav destinations. */+@Composable+private fun editorCommands(+    actions: CodeActions,+    onToggleFind: () -> Unit,+    onGoToLine: () -> Unit,+    onQuickOpen: () -> Unit,+    onOpenSearch: () -> Unit,+    onOpenGit: () -> Unit,+    onOpenTerminal: () -> Unit,+    onOpenPreview: () -> Unit,+    onOpenSettings: () -> Unit,+    onOpenFolder: () -> Unit,+    onOpenFile: () -> Unit,+): List<PickerItem> = listOf(+    PickerItem(stringResource(R.string.quick_open)) { onQuickOpen() },+    PickerItem(stringResource(R.string.save)) { actions.save() },+    PickerItem(stringResource(R.string.find)) { onToggleFind() },+    PickerItem(stringResource(R.string.go_to_line)) { onGoToLine() },+    PickerItem(stringResource(R.string.toggle_comment)) { actions.toggleComment() },+    PickerItem(stringResource(R.string.duplicate_line)) { actions.duplicateLine() },+    PickerItem(stringResource(R.string.move_line_up)) { actions.moveLineUp() },+    PickerItem(stringResource(R.string.move_line_down)) { actions.moveLineDown() },+    PickerItem(stringResource(R.string.delete_line)) { actions.deleteLine() },+    PickerItem(stringResource(R.string.format_document)) { actions.formatDocument() },+    PickerItem(stringResource(R.string.soft_wrap)) { actions.toggleSoftWrap() },+    PickerItem(stringResource(R.string.undo)) { actions.undo() },+    PickerItem(stringResource(R.string.redo)) { actions.redo() },+    PickerItem(stringResource(R.string.search_in_project)) { onOpenSearch() },+    PickerItem(stringResource(R.string.source_control)) { onOpenGit() },+    PickerItem(stringResource(R.string.terminal)) { onOpenTerminal() },+    PickerItem(stringResource(R.string.preview)) { onOpenPreview() },+    PickerItem(stringResource(R.string.settings)) { onOpenSettings() },+    PickerItem(stringResource(R.string.open_folder)) { onOpenFolder() },+    PickerItem(stringResource(R.string.open_file)) { onOpenFile() },+)
code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.ktindex 61de41ec3c..95ccbf661f 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -35,6 +35,14 @@ data class TreeRowUiState(     val expanded: Boolean = false, ) +/** One file under the open project, used by quick-open and the recent-files list. */+data class ProjectFileEntry(+    val path: String,+    val name: String,+    /** Path relative to the project root, shown as the secondary line in quick-open. */+    val relativePath: String,+)+ /** One hit from a project-wide search: the file path, the 1-based line and a preview of that line. */ data class SearchResult(     val path: String,@@ -62,6 +70,10 @@ data class CodeUiState(     val completions: List<Completion> = emptyList(),     val showCompletions: Boolean = false,     val editorTheme: String = EditorThemes.DEFAULT,+    /** All files under the open project, for quick-open (built lazily, cached in the ViewModel). */+    val projectFiles: List<ProjectFileEntry> = emptyList(),+    /** Most-recently-opened files, newest first, shown in quick-open when the query is empty. */+    val recentFiles: List<ProjectFileEntry> = emptyList(), ) {     val currentTab: TabUiState? get() = tabs.getOrNull(currentIndex) }@@ -143,6 +155,14 @@ interface CodeActions {     /** Open the file for a search result and jump to its line. */     fun openSearchResult(result: SearchResult) {} +    // ---- Quick-open ----++    /** Open a file by absolute path (from quick-open or the recent-files list). */+    fun openPath(path: String) {}++    /** Rebuild the cached [CodeUiState.projectFiles] list (called when quick-open is shown). */+    fun refreshProjectFiles() {}+     // ---- File operations ----      /** Create a file under the given parent row (null = tree root) and open it in a tab. */
code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.ktindex 1cd6f7c0e0..b1334c47d2 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -43,6 +43,11 @@ class EditorPrefs(context: Context) {     /** File path of the tab that was in the foreground, for session restore. */     val sessionCurrent: Flow<String?> = appContext.editorDataStore.data.map { it[SESSION_CURRENT_KEY] } +    /** Most-recently-opened file paths, newest first, for quick-open. */+    val recentFiles: Flow<List<String>> = appContext.editorDataStore.data.map { prefs ->+        prefs[RECENT_FILES_KEY]?.split("\n")?.filter { it.isNotEmpty() } ?: emptyList()+    }+     // Git remote credentials + author. DataStore is not encrypted; acceptable for F-Droid/local.     val gitUsername: Flow<String> = appContext.editorDataStore.data.map { it[GIT_USERNAME_KEY] ?: "" }     val gitToken: Flow<String> = appContext.editorDataStore.data.map { it[GIT_TOKEN_KEY] ?: "" }@@ -102,6 +107,14 @@ class EditorPrefs(context: Context) {         appContext.editorDataStore.edit { it[GIT_USERNAME_KEY] = value }     } +    /** Persists the recent-file list (newest first); clears the key when empty. */+    suspend fun setRecentFiles(paths: List<String>) {+        appContext.editorDataStore.edit { prefs ->+            if (paths.isEmpty()) prefs.remove(RECENT_FILES_KEY)+            else prefs[RECENT_FILES_KEY] = paths.joinToString("\n")+        }+    }+     suspend fun setGitToken(value: String) {         appContext.editorDataStore.edit { it[GIT_TOKEN_KEY] = value }     }@@ -132,6 +145,7 @@ class EditorPrefs(context: Context) {         private val EDITOR_THEME_KEY = stringPreferencesKey("editor_theme")         private val SESSION_PATHS_KEY = stringPreferencesKey("session_paths")         private val SESSION_CURRENT_KEY = stringPreferencesKey("session_current")+        private val RECENT_FILES_KEY = stringPreferencesKey("recent_files")         private val GIT_USERNAME_KEY = stringPreferencesKey("git_username")         private val GIT_TOKEN_KEY = stringPreferencesKey("git_token")         private val GIT_AUTHOR_NAME_KEY = stringPreferencesKey("git_author_name")
code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.ktindex e635e256d2..e8c4a2affa 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -187,6 +187,11 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         private set     private var terminal: TerminalSession? = null +    // ---- Quick-open ----+    val projectFiles = mutableStateListOf<ProjectFileEntry>()+    private val recentPaths = mutableStateListOf<String>()+    private var projectFilesJob: Job? = null+     /** Snapshot of everything the screens draw; rebuilt on every read, as Compose expects. */     val uiState: CodeUiState         get() = CodeUiState(@@ -221,6 +226,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             completions = completions.toList(),             showCompletions = showCompletions,             editorTheme = editorTheme,+            projectFiles = projectFiles.toList(),+            recentFiles = recentPaths.map { toProjectEntry(File(it)) },         )      init {@@ -236,6 +243,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         viewModelScope.launch { _gitToken.value = prefs.gitToken.first() }         viewModelScope.launch { _gitAuthorName.value = prefs.gitAuthorName.first() }         viewModelScope.launch { _gitAuthorEmail.value = prefs.gitAuthorEmail.first() }+        viewModelScope.launch { recentPaths.addAll(prefs.recentFiles.first()) }         viewModelScope.launch {             val stored = prefs.folderPath.first() ?: return@launch             val dir = File(stored)@@ -467,6 +475,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),      /** Opens [file] in a tab (focusing it if already open), reading its text off the main thread. */     fun openFile(file: File) {+        addRecentFile(file.absolutePath)         val key = file.absolutePath         val existing = tabs.indexOfFirst { it.key == key }         if (existing >= 0) {@@ -974,6 +983,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),     }      override fun openSearchResult(result: SearchResult) {+        addRecentFile(result.path)         val existing = tabs.indexOfFirst { it.key == result.path }         if (existing >= 0) {             currentIndex = existing@@ -992,6 +1002,60 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         }     } +    // ---- Quick-open ----++    override fun openPath(path: String) = openFile(File(path))++    /** Rebuilds the cached project-file list by walking the open folder off the main thread. */+    override fun refreshProjectFiles() {+        val root = rootDir ?: return+        projectFilesJob?.cancel()+        projectFilesJob = viewModelScope.launch {+            val collected = withContext(Dispatchers.IO) {+                val out = ArrayList<ProjectFileEntry>()+                val rootPath = root.absolutePath+                val stack = ArrayDeque<File>()+                stack.addLast(root)+                while (stack.isNotEmpty() && out.size < MAX_PROJECT_FILES) {+                    coroutineContext.ensureActive()+                    val dir = stack.removeLast()+                    val children = runCatching { FileFiles.listChildren(dir) }.getOrDefault(emptyList())+                    for (child in children) {+                        if (out.size >= MAX_PROJECT_FILES) break+                        if (child.isDirectory) {+                            if (child.name !in SKIP_DIRS) stack.addLast(child.file)+                            continue+                        }+                        out.add(toProjectEntry(child.file))+                    }+                }+                out.sortedBy { it.relativePath.lowercase() }+            }+            projectFiles.clear()+            projectFiles.addAll(collected)+        }+    }++    /** Builds the display entry for [file], with a path relative to the open root when possible. */+    private fun toProjectEntry(file: File): ProjectFileEntry {+        val abs = file.absolutePath+        val rootPath = rootDir?.absolutePath+        val rel = if (rootPath != null && abs.startsWith(rootPath + File.separator)) {+            abs.substring(rootPath.length + 1)+        } else {+            abs+        }+        return ProjectFileEntry(abs, file.name, rel)+    }++    /** Records [path] as the most-recently-opened file and persists the capped list. */+    private fun addRecentFile(path: String) {+        recentPaths.remove(path)+        recentPaths.add(0, path)+        while (recentPaths.size > MAX_RECENT_FILES) recentPaths.removeAt(recentPaths.lastIndex)+        viewModelScope.launch { prefs.setRecentFiles(recentPaths.toList()) }+    }+     private companion object {         const val AUTO_SAVE_DELAY_MS = 1500L         const val MIN_COMPLETION_PREFIX = 1@@ -1001,6 +1065,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         const val MAX_SEARCH_RESULTS = 500         const val MAX_MATCHES_PER_FILE = 50         const val MAX_SEARCH_FILE_SIZE = 500_000+        const val MAX_PROJECT_FILES = 5000+        const val MAX_RECENT_FILES = 15         val SKIP_DIRS = setOf(".git", "node_modules", "build", ".gradle", ".idea")     } }
code/src/main/java/com/vayunmathur/code/util/FuzzyMatch.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/FuzzyMatch.kt b/code/src/main/java/com/vayunmathur/code/util/FuzzyMatch.ktnew file mode 100644index 0000000000..7fb6dc56e1--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/FuzzyMatch.kt@@ -0,0 +1,105 @@+package com.vayunmathur.code.util++/**+ * A subsequence fuzzy matcher for quick-open and the command palette.+ *+ * [fuzzyScore] returns how well [query] matches [candidate] (higher is better), or null when the+ * query is not a subsequence of the candidate. Matching is case-insensitive; matches at word+ * boundaries (string start, after a separator, or a camelCase hump), consecutive runs and+ * exact-case hits score higher, while gaps before and between matches are penalized. Pure — no+ * Android dependencies — so it can be unit-tested in isolation.+ *+ * Scoring uses a sparse dynamic program over the positions where each query character occurs, so+ * it finds the best alignment (e.g. "ce" prefers the C/E camel humps of "CodeEditor") rather than+ * greedily taking the first occurrence.+ */++private val SEPARATORS = charArrayOf('/', '\\', '_', '-', '.', ' ')++private const val MATCH_SCORE = 16+private const val BOUNDARY_BONUS = 12+private const val CONSECUTIVE_BONUS = 15+private const val CASE_BONUS = 2+private const val GAP_START_PENALTY = 3+private const val GAP_EXTEND_PENALTY = 1+private const val MAX_LEADING_GAP_PENALTY = 10+private const val LENGTH_TIE_BREAKER = 8++private fun Char.matchesIgnoreCase(other: Char): Boolean =+    this == other || this.lowercaseChar() == other.lowercaseChar()++/** True when [candidate] index [i] begins a "word": string start, post-separator, or camel hump. */+private fun isBoundary(candidate: String, i: Int): Boolean {+    if (i == 0) return true+    val prev = candidate[i - 1]+    if (prev in SEPARATORS) return true+    return (prev.isLowerCase() || prev.isDigit()) && candidate[i].isUpperCase()+}++private fun gapPenalty(gap: Int): Int =+    if (gap <= 0) 0 else GAP_START_PENALTY + (gap - 1) * GAP_EXTEND_PENALTY++/**+ * Relevance of [query] against [candidate], or null when [query] is not a subsequence. An empty+ * query matches everything with a neutral score of 0.+ */+fun fuzzyScore(query: String, candidate: String): Int? {+    if (query.isEmpty()) return 0+    if (candidate.length < query.length) return null++    // For query char qi, `positions` are the candidate indices where it matches and `scores` the+    // best score for an alignment ending at that index. Each layer only depends on the previous.+    var prevScores = IntArray(0)+    var prevPositions = IntArray(0)++    for (qi in query.indices) {+        val qc = query[qi]+        val positions = ArrayList<Int>()+        val scores = ArrayList<Int>()+        for (ci in candidate.indices) {+            if (!candidate[ci].matchesIgnoreCase(qc)) continue+            var charScore = MATCH_SCORE+            if (isBoundary(candidate, ci)) charScore += BOUNDARY_BONUS+            if (candidate[ci] == qc) charScore += CASE_BONUS++            val best: Int? = if (qi == 0) {+                charScore - minOf(ci, MAX_LEADING_GAP_PENALTY)+            } else {+                var b = Int.MIN_VALUE+                for (k in prevPositions.indices) {+                    val pj = prevPositions[k]+                    if (pj >= ci) break // positions are ascending; no earlier predecessor remains+                    val gap = ci - pj - 1+                    val consecutive = if (gap == 0) CONSECUTIVE_BONUS else 0+                    val cand = prevScores[k] + charScore + consecutive - gapPenalty(gap)+                    if (cand > b) b = cand+                }+                if (b == Int.MIN_VALUE) null else b+            }+            if (best != null) {+                positions.add(ci)+                scores.add(best)+            }+        }+        if (positions.isEmpty()) return null+        prevPositions = positions.toIntArray()+        prevScores = scores.toIntArray()+    }++    val best = prevScores.maxOrNull() ?: return null+    // Mild preference for shorter candidates when scores are otherwise equal.+    return best - candidate.length / LENGTH_TIE_BREAKER+}++/**+ * Filters and ranks [candidates] by [fuzzyScore] of [key] against [query], best first. Ties are+ * broken by shorter candidates, then by original order (the sort is stable). A blank query returns+ * the list unchanged (callers show it as-is).+ */+fun <T> fuzzyRank(query: String, candidates: List<T>, key: (T) -> String): List<T> {+    if (query.isBlank()) return candidates+    return candidates+        .mapNotNull { item -> fuzzyScore(query, key(item))?.let { Triple(item, it, key(item).length) } }+        .sortedWith(compareByDescending<Triple<T, Int, Int>> { it.second }.thenBy { it.third })+        .map { it.first }+}
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlindex d39db534b0..14dfa63843 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -88,4 +88,11 @@     <string name="preview_no_file">Open a file to preview.</string>     <string name="preview_unsupported">No preview for %1$s files.</string>     <string name="format_document">Format document</string>+    <string name="quick_open">Quick open</string>+    <string name="quick_open_hint">Type a file name</string>+    <string name="command_palette">Command palette</string>+    <string name="command_palette_hint">Type a command</string>+    <string name="save">Save</string>+    <string name="undo">Undo</string>+    <string name="redo">Redo</string> </resources>
code/src/test/java/com/vayunmathur/code/util/FuzzyMatchTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/FuzzyMatchTest.kt b/code/src/test/java/com/vayunmathur/code/util/FuzzyMatchTest.ktnew file mode 100644index 0000000000..8f96ff0f4d--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/FuzzyMatchTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.code.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Unit tests for the pure fuzzy matcher used by quick-open and the command palette. */+class FuzzyMatchTest {++    @Test+    fun emptyQueryMatchesEverythingNeutrally() {+        assertEquals(0, fuzzyScore("", "anything"))+    }++    @Test+    fun nonSubsequenceReturnsNull() {+        assertNull(fuzzyScore("xyz", "CodeEditor"))+        assertNull(fuzzyScore("edroc", "code"))+        // Query longer than candidate can never be a subsequence.+        assertNull(fuzzyScore("codes", "code"))+    }++    @Test+    fun subsequenceMatches() {+        assertNotNull(fuzzyScore("cdr", "CodeEditor"))+        assertNotNull(fuzzyScore("code", "CodeEditor"))+    }++    @Test+    fun matchingIsCaseInsensitive() {+        assertNotNull(fuzzyScore("CODE", "code.kt"))+        assertNotNull(fuzzyScore("code", "CODE.KT"))+    }++    @Test+    fun consecutivePrefixBeatsScatteredMatch() {+        val prefix = fuzzyScore("code", "code.kt")!!+        val scattered = fuzzyScore("code", "c_o_d_e.kt")!!+        assertTrue(prefix > scattered, "prefix=$prefix scattered=$scattered")+    }++    @Test+    fun camelCaseHumpsScoreHigherThanBuriedLetters() {+        val humps = fuzzyScore("ce", "CodeEditor")!!+        val buried = fuzzyScore("ce", "coreachievement")!!+        assertTrue(humps > buried, "humps=$humps buried=$buried")+    }++    @Test+    fun filenameBoundaryPreferred() {+        // Matching the file name segment should beat matching across the directory prefix.+        val onName = fuzzyScore("model", "src/util/DiffModel.kt")!!+        val onlyExisting = fuzzyScore("model", "src/util/DiffModel.kt")+        assertNotNull(onlyExisting)+        assertTrue(onName > 0)+    }++    @Test+    fun rankOrdersBestFirst() {+        val files = listOf("app/EditorViewModel.kt", "ed.txt", "code/Editor.kt", "readme.md")+        val ranked = fuzzyRank("edi", files) { it }+        assertEquals("code/Editor.kt", ranked.first())+        assertTrue("readme.md" !in ranked) // no subsequence -> filtered out+    }++    @Test+    fun blankQueryReturnsListUnchanged() {+        val files = listOf("b", "a", "c")+        assertEquals(files, fuzzyRank("  ", files) { it })+    }++    @Test+    fun rankIsStableOnTies() {+        val items = listOf("ab1", "ab2", "ab3")+        assertEquals(items, fuzzyRank("ab", items) { it })+    }+}