code: wire file ops, settings, search and editor UX into screens
- Commit
cc03e576099f6ebae8658122786ae3badfce5b13- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 20:38 UTC (4 months ago)
- Parents
15b1590
Diff
code/src/main/java/com/vayunmathur/code/MainActivity.kt
diff --git a/code/src/main/java/com/vayunmathur/code/MainActivity.kt b/code/src/main/java/com/vayunmathur/code/MainActivity.ktindex 36db48c638..3deac3477b 100644--- a/code/src/main/java/com/vayunmathur/code/MainActivity.kt+++ b/code/src/main/java/com/vayunmathur/code/MainActivity.kt@@ -8,10 +8,14 @@ import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.compose.runtime.Composable import com.vayunmathur.code.ui.EditorPage+import com.vayunmathur.code.ui.SearchPage+import com.vayunmathur.code.ui.SettingsPage+import com.vayunmathur.code.util.EditorPrefs import com.vayunmathur.code.util.EditorViewModel import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.openSettingsIfRequested import com.vayunmathur.library.util.rememberNavBackStack import kotlinx.serialization.Serializable @@ -23,7 +27,12 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() handleIntent(intent) setContent {- DynamicTheme {+ val darkTheme = when (viewModel.themeMode) {+ EditorPrefs.THEME_LIGHT -> false+ EditorPrefs.THEME_DARK -> true+ else -> null+ }+ DynamicTheme(darkTheme = darkTheme) { Navigation(viewModel) } }@@ -47,12 +56,28 @@ class MainActivity : ComponentActivity() { sealed interface Route : NavKey { @Serializable data object Editor : Route++ @Serializable+ data object Settings : Route++ @Serializable+ data object Search : Route } @Composable fun Navigation(viewModel: EditorViewModel) { val backStack = rememberNavBackStack<Route>(Route.Editor)+ // Land on settings when opened from the system App Info page.+ backStack.openSettingsIfRequested(Route.Settings) MainNavigation(backStack) {- entry<Route.Editor> { EditorPage(viewModel) }+ entry<Route.Editor> {+ EditorPage(+ viewModel,+ onOpenSettings = { backStack.add(Route.Settings) },+ onOpenSearch = { backStack.add(Route.Search) },+ )+ }+ entry<Route.Settings> { SettingsPage(viewModel, backStack) }+ entry<Route.Search> { SearchPage(viewModel, backStack) } } }
code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.ktindex 7c48d85f1a..7d633f1c59 100644--- a/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -4,7 +4,6 @@ import androidx.compose.ui.res.stringResource import com.vayunmathur.code.R import androidx.compose.foundation.horizontalScroll 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@@ -59,6 +58,7 @@ fun CodeEditor( showFind: Boolean, onCloseFind: () -> Unit, modifier: Modifier = Modifier,+ fontSize: Int = 14, /** Preview seam: the query the find bar starts on. The app always starts it empty. */ initialQuery: String = "", ) {@@ -68,12 +68,24 @@ fun CodeEditor( var query by remember(tab.name) { mutableStateOf(initialQuery) } var replacement by remember(tab.name) { mutableStateOf("") } var caseSensitive by remember(tab.name) { mutableStateOf(false) }+ var useRegex by remember(tab.name) { mutableStateOf(false) } var activeMatch by remember(tab.name) { mutableStateOf(0) } val text = tab.value.text- val matches = remember(text, query, caseSensitive) {+ val regexValid = remember(query, useRegex) {+ !useRegex || query.isEmpty() || runCatching { Regex(query) }.isSuccess+ }+ val matches = remember(text, query, caseSensitive, useRegex) { if (query.isEmpty()) { emptyList()+ } else if (useRegex) {+ runCatching {+ val options = if (caseSensitive) emptySet() else setOf(RegexOption.IGNORE_CASE)+ Regex(query, options).findAll(text)+ .map { it.range }+ .filter { !it.isEmpty() }+ .toList()+ }.getOrDefault(emptyList()) } else { val found = ArrayList<IntRange>() var i = text.indexOf(query, 0, ignoreCase = !caseSensitive)@@ -104,19 +116,32 @@ fun CodeEditor( query = query, replacement = replacement, caseSensitive = caseSensitive,+ useRegex = useRegex,+ regexValid = regexValid, matchCount = matches.size, activeMatch = activeMatch, onQueryChange = { query = it; activeMatch = 0 }, onReplacementChange = { replacement = it }, onToggleCase = { caseSensitive = !caseSensitive },+ onToggleRegex = { useRegex = !useRegex; activeMatch = 0 }, onNext = { goTo(activeMatch + 1) }, onPrev = { goTo(activeMatch - 1) }, onReplace = { if (matches.isNotEmpty()) {- actions.replaceRange(matches[activeMatch], replacement)+ if (useRegex) {+ actions.replaceMatchRegex(matches[activeMatch], query, replacement, caseSensitive)+ } else {+ actions.replaceRange(matches[activeMatch], replacement)+ }+ }+ },+ onReplaceAll = {+ if (useRegex) {+ actions.replaceAllRegex(query, replacement, caseSensitive)+ } else {+ actions.replaceAll(matches, replacement) } },- onReplaceAll = { actions.replaceAll(matches, replacement) }, onClose = onCloseFind, ) HorizontalDivider()@@ -124,8 +149,8 @@ fun CodeEditor( val editorStyle = TextStyle( fontFamily = FontFamily.Monospace,- fontSize = 14.sp,- lineHeight = 20.sp,+ fontSize = fontSize.sp,+ lineHeight = (fontSize * 1.4f).sp, color = MaterialTheme.colorScheme.onSurface, ) val syntaxColors = rememberSyntaxColors()@@ -184,11 +209,14 @@ private fun FindBar( query: String, replacement: String, caseSensitive: Boolean,+ useRegex: Boolean,+ regexValid: Boolean, matchCount: Int, activeMatch: Int, onQueryChange: (String) -> Unit, onReplacementChange: (String) -> Unit, onToggleCase: () -> Unit,+ onToggleRegex: () -> Unit, onNext: () -> Unit, onPrev: () -> Unit, onReplace: () -> Unit,@@ -203,6 +231,12 @@ private fun FindBar( modifier = Modifier.weight(1f), placeholder = { Text(stringResource(R.string.find)) }, singleLine = true,+ isError = !regexValid,+ supportingText = if (!regexValid) {+ { Text(stringResource(R.string.invalid_regex)) }+ } else {+ null+ }, ) val label = if (matchCount == 0) "0/0" else "${activeMatch + 1}/$matchCount" Text(label, modifier = Modifier.padding(horizontal = 8.dp))@@ -222,10 +256,29 @@ private fun FindBar( TextButton(onClick = onReplace, enabled = matchCount > 0) { Text(stringResource(R.string.replace)) } TextButton(onClick = onReplaceAll, enabled = matchCount > 0) { Text(stringResource(R.string.all)) } }- Box {- TextButton(onClick = onToggleCase) {- Text(if (caseSensitive) "Case: On" else "Case: Off")- }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ ToggleChip(+ label = stringResource(R.string.match_case),+ selected = caseSensitive,+ onClick = onToggleCase,+ )+ ToggleChip(+ label = stringResource(R.string.use_regex),+ selected = useRegex,+ onClick = onToggleRegex,+ ) } } }++/** A small text toggle that colours itself when active; used for the find-bar options. */+@Composable+private fun ToggleChip(label: String, selected: Boolean, onClick: () -> Unit) {+ TextButton(onClick = onClick) {+ Text(+ label,+ color = if (selected) MaterialTheme.colorScheme.primary+ else MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}
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 fc0374eb31..4629e5e7c6 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -35,6 +35,8 @@ import com.vayunmathur.code.util.CodeActions import com.vayunmathur.code.util.CodeUiState import com.vayunmathur.code.util.EditorViewModel import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.ConfirmDialog import com.vayunmathur.library.ui.DrawerValue import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton@@ -43,15 +45,20 @@ import com.vayunmathur.library.ui.IconCode import com.vayunmathur.library.ui.IconFindReplace import com.vayunmathur.library.ui.IconFormatIndentIncrease 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.IconSettings import com.vayunmathur.library.ui.IconUndo import com.vayunmathur.library.ui.IconWrapText import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.ModalDrawerSheet import com.vayunmathur.library.ui.ModalNavigationDrawer+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.OverflowMenu import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.rememberDrawerState import kotlinx.coroutines.launch@@ -63,7 +70,11 @@ import kotlinx.coroutines.launch * exactly what a `@Preview` cannot provide. */ @Composable-fun EditorPage(viewModel: EditorViewModel) {+fun EditorPage(+ viewModel: EditorViewModel,+ onOpenSettings: () -> Unit = {},+ onOpenSearch: () -> Unit = {},+) { val folderLauncher = rememberLauncherForActivityResult( ActivityResultContracts.OpenDocumentTree() ) { uri -> uri?.let(viewModel::openFolder) }@@ -77,6 +88,8 @@ fun EditorPage(viewModel: EditorViewModel) { actions = viewModel, onOpenFolder = { folderLauncher.launch(null) }, onOpenFile = { fileLauncher.launch(arrayOf("*/*")) },+ onOpenSettings = onOpenSettings,+ onOpenSearch = onOpenSearch, ) } @@ -94,6 +107,8 @@ fun EditorScreen( actions: CodeActions, onOpenFolder: () -> Unit = {}, onOpenFile: () -> Unit = {},+ onOpenSettings: () -> Unit = {},+ onOpenSearch: () -> Unit = {}, /** * Seeds for the screen's own UI-only state (is the drawer showing, is the find bar open * and on what query). The app always takes the defaults; previews set them so a given@@ -129,6 +144,9 @@ fun EditorScreen( navigationIcon = { IconButton(onClick = { scope.launch { drawerState.open() } }) { IconMenu() } },+ actions = {+ IconButton(onClick = onOpenSettings) { IconSettings() }+ }, ) }, ) { padding ->@@ -139,12 +157,18 @@ fun EditorScreen( } else { TabStrip(state, actions) HorizontalDivider()- EditorToolbar(state = state, actions = actions, onToggleFind = { showFind = !showFind })+ EditorToolbar(+ state = state,+ actions = actions,+ onToggleFind = { showFind = !showFind },+ onOpenSearch = onOpenSearch,+ ) HorizontalDivider() CodeEditor( tab = tab, actions = actions, softWrap = state.softWrap,+ fontSize = state.fontSize, showFind = showFind, onCloseFind = { showFind = false }, modifier = Modifier.weight(1f),@@ -183,6 +207,7 @@ private fun EmptyEditorState(onOpenFolder: () -> Unit, onOpenFile: () -> Unit) { /** Horizontally scrollable strip of open tabs, each with a dirty indicator and close button. */ @Composable private fun TabStrip(state: CodeUiState, actions: CodeActions) {+ var pendingCloseIndex by remember { mutableStateOf<Int?>(null) } Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) { state.tabs.forEachIndexed { index, tab -> val selected = index == state.currentIndex@@ -211,18 +236,40 @@ private fun TabStrip(state: CodeUiState, actions: CodeActions) { .background(MaterialTheme.colorScheme.primary) ) }- IconButton(onClick = { actions.closeTab(index) }, modifier = Modifier.size(32.dp)) {+ IconButton(+ onClick = {+ if (tab.isDirty) pendingCloseIndex = index else actions.closeTab(index)+ },+ modifier = Modifier.size(32.dp),+ ) { IconClose(Modifier.size(16.dp)) } } } }++ pendingCloseIndex?.let { index ->+ ConfirmDialog(+ title = stringResource(R.string.discard_changes_title),+ confirmLabel = stringResource(R.string.discard),+ dismissLabel = stringResource(R.string.cancel),+ destructive = true,+ onConfirm = { actions.closeTab(index) },+ onDismiss = { pendingCloseIndex = null },+ )+ } } -/** Undo/redo, save, find, soft-wrap, tab-insert and a language indicator. */+/** Undo/redo, save, find, soft-wrap, tab-insert, an overflow menu and a language indicator. */ @Composable-private fun EditorToolbar(state: CodeUiState, actions: CodeActions, onToggleFind: () -> Unit) {+private fun EditorToolbar(+ state: CodeUiState,+ actions: CodeActions,+ onToggleFind: () -> Unit,+ onOpenSearch: () -> Unit = {},+) { val tab = state.currentTab ?: return+ var showGoToLine by remember { mutableStateOf(false) } Row( modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), verticalAlignment = Alignment.CenterVertically,@@ -237,7 +284,11 @@ private fun EditorToolbar(state: CodeUiState, actions: CodeActions, onToggleFind else MaterialTheme.colorScheme.onSurfaceVariant, ) }- IconButton(onClick = { actions.insertText(" ") }) { IconFormatIndentIncrease() }+ 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.search_in_project)) { onOpenSearch() }+ } Spacer(Modifier.width(8.dp)) Text( text = tab.language.label,@@ -246,4 +297,39 @@ private fun EditorToolbar(state: CodeUiState, actions: CodeActions, onToggleFind 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. */+@Composable+private fun GoToLineDialog(onGo: (Int) -> Unit, onDismiss: () -> Unit) {+ var value by remember { mutableStateOf("") }+ val line = value.toIntOrNull()+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(R.string.go_to_line)) },+ text = {+ OutlinedTextField(+ value = value,+ onValueChange = { new -> value = new.filter { it.isDigit() } },+ singleLine = true,+ label = { Text(stringResource(R.string.line)) },+ )+ },+ confirmButton = {+ TextButton(+ onClick = { line?.let(onGo); onDismiss() },+ enabled = line != null && line > 0,+ ) { Text(stringResource(R.string.go)) }+ },+ dismissButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+ },+ ) }
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 2e63da34d6..9c74e4a5fd 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -2,6 +2,7 @@ package com.vayunmathur.code.util import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue+import android.net.Uri import com.vayunmathur.code.syntax.Language /**@@ -34,6 +35,14 @@ data class TreeRowUiState( val expanded: Boolean = false, ) +/** One hit from a project-wide search: the file, the 1-based line and a preview of that line. */+data class SearchResult(+ val uri: Uri,+ val name: String,+ val line: Int,+ val preview: String,+)+ /** Everything the editor screen draws. */ data class CodeUiState( val tabs: List<TabUiState> = emptyList(),@@ -44,6 +53,12 @@ data class CodeUiState( /** False until a folder has been picked, which is when the tree replaces its empty state. */ val folderOpen: Boolean = false, val nodes: List<TreeRowUiState> = emptyList(),+ val fontSize: Int = 14,+ val tabWidth: Int = 4,+ val autoIndent: Boolean = true,+ val autoCloseBrackets: Boolean = true,+ val searchResults: List<SearchResult> = emptyList(),+ val isSearching: Boolean = false, ) { val currentTab: TabUiState? get() = tabs.getOrNull(currentIndex) }@@ -72,9 +87,48 @@ interface CodeActions { /** Move the selection without recording an undo step (used by find navigation). */ fun setSelection(range: TextRange) {} + /** Move the caret to the start of [line] (1-based). */+ fun goToLine(line: Int) {}+ fun replaceRange(range: IntRange, replacement: String) {} fun replaceAll(matches: List<IntRange>, replacement: String) {} + /** Replace the match at [range] using regex substitution (supports `$1` group refs). */+ fun replaceMatchRegex(range: IntRange, pattern: String, replacement: String, caseSensitive: Boolean) {}++ /** Replace every regex match in the current file (supports `$1` group refs). */+ fun replaceAllRegex(pattern: String, replacement: String, caseSensitive: Boolean) {}++ // ---- Project search ----++ /** Search every text file under the open folder for [query]. */+ fun searchProject(query: String, caseSensitive: Boolean, useRegex: Boolean) {}++ /** Open the file for a search result and jump to its line. */+ fun openSearchResult(result: SearchResult) {}++ // ---- File operations ----++ /** Create a file under the given parent row (null = tree root) and open it in a tab. */+ fun createFile(parentIndex: Int?, name: String) {}++ /** Create a folder under the given parent row (null = tree root). */+ fun createFolder(parentIndex: Int?, name: String) {}++ /** Rename the file/folder at [index]. */+ fun renameNode(index: Int, newName: String) {}++ /** Delete the file/folder at [index], closing any tabs it (or its descendants) backs. */+ fun deleteNode(index: Int) {}++ // ---- Settings ----++ fun setFontSize(size: Int) {}+ fun setTabWidth(width: Int) {}+ fun setThemeMode(mode: String) {}+ fun setAutoIndent(enabled: Boolean) {}+ fun setAutoCloseBrackets(enabled: Boolean) {}+ companion object { val Noop: CodeActions = object : CodeActions {} }
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 98f73cbb3f..7f3b81ce4d 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -3,6 +3,7 @@ package com.vayunmathur.code.util import android.app.Application import android.content.Intent import android.net.Uri+import android.provider.DocumentsContract import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf@@ -14,9 +15,12 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.code.syntax.Language import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import kotlin.coroutines.coroutineContext /** One expandable row in the file-tree pane; the tree is stored as a flat, ordered list. */ class TreeNode(val entry: DocEntry, val depth: Int) {@@ -30,12 +34,14 @@ class TreeNode(val entry: DocEntry, val depth: Int) { * [canUndo]/[canRedo] mirror their emptiness as state so the toolbar buttons stay reactive. */ class OpenTab(- val uri: Uri,+ uri: Uri, initialName: String, initialText: String,- val language: Language,+ language: Language, ) {+ var uri by mutableStateOf(uri) var name by mutableStateOf(initialName)+ var language by mutableStateOf(language) var value by mutableStateOf(TextFieldValue(initialText)) var savedText by mutableStateOf(initialText) var canUndo by mutableStateOf(false)@@ -96,6 +102,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), private set var rootName by mutableStateOf<String?>(null) private set+ private var rootDocumentId: String? = null val nodes = mutableStateListOf<TreeNode>() // ---- Tabs ----@@ -107,6 +114,22 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), // ---- Preferences ---- var softWrap by mutableStateOf(false) private set+ var fontSize by mutableStateOf(EditorPrefs.DEFAULT_FONT_SIZE)+ private set+ var tabWidth by mutableStateOf(EditorPrefs.DEFAULT_TAB_WIDTH)+ private set+ var themeMode by mutableStateOf(EditorPrefs.THEME_SYSTEM)+ private set+ var autoIndent by mutableStateOf(true)+ private set+ var autoCloseBrackets by mutableStateOf(true)+ private set++ // ---- Project search ----+ val searchResults = mutableStateListOf<SearchResult>()+ var isSearching by mutableStateOf(false)+ private set+ private var searchJob: Job? = null /** Snapshot of everything the screens draw; rebuilt on every read, as Compose expects. */ val uiState: CodeUiState@@ -133,10 +156,21 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), expanded = it.expanded, ) },+ fontSize = fontSize,+ tabWidth = tabWidth,+ autoIndent = autoIndent,+ autoCloseBrackets = autoCloseBrackets,+ searchResults = searchResults.toList(),+ isSearching = isSearching, ) init { viewModelScope.launch { softWrap = prefs.softWrap.first() }+ viewModelScope.launch { fontSize = prefs.fontSize.first() }+ viewModelScope.launch { tabWidth = prefs.tabWidth.first() }+ viewModelScope.launch { themeMode = prefs.themeMode.first() }+ viewModelScope.launch { autoIndent = prefs.autoIndent.first() }+ viewModelScope.launch { autoCloseBrackets = prefs.autoCloseBrackets.first() } viewModelScope.launch { val stored = prefs.folderUri.first() ?: return@launch val uri = stored.toUri()@@ -160,6 +194,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), fun closeFolder() { treeUri = null rootName = null+ rootDocumentId = null nodes.clear() viewModelScope.launch { prefs.clearFolderUri() } }@@ -169,6 +204,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val children = withContext(Dispatchers.IO) { SafFiles.listChildren(context, uri, root.documentId) } treeUri = uri rootName = root.name+ rootDocumentId = root.documentId nodes.clear() nodes.addAll(children.map { TreeNode(it, depth = 0) }) }@@ -184,9 +220,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), if (node.expanded) { node.expanded = false- while (index + 1 < nodes.size && nodes[index + 1].depth > node.depth) {- nodes.removeAt(index + 1)- }+ removeDescendants(index) } else { node.expanded = true node.loading = true@@ -204,6 +238,147 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), } } + // ---- File operations ----++ /** Removes the rows that are descendants of the row at [index] (depth strictly greater). */+ private fun removeDescendants(index: Int) {+ val depth = nodes[index].depth+ while (index + 1 < nodes.size && nodes[index + 1].depth > depth) {+ nodes.removeAt(index + 1)+ }+ }++ /**+ * Re-lists the children of a folder and rebuilds that subtree in [nodes]. Expansion state+ * and already-loaded descendant rows of immediate child folders are preserved by document id.+ * [parentIndex] null refreshes the tree root.+ */+ private suspend fun refreshChildren(parentIndex: Int?) {+ val tree = treeUri ?: return+ val parentDocId = if (parentIndex == null) rootDocumentId ?: return+ else nodes.getOrNull(parentIndex)?.entry?.documentId ?: return+ val parentDepth = if (parentIndex == null) -1 else nodes[parentIndex].depth+ val childDepth = parentDepth + 1++ val blockStart = (parentIndex ?: -1) + 1+ var blockEnd = blockStart+ while (blockEnd < nodes.size && nodes[blockEnd].depth > parentDepth) blockEnd++++ // Preserve existing immediate children (and their loaded subtrees) by document id.+ val preservedNode = HashMap<String, TreeNode>()+ val preservedSubtree = HashMap<String, List<TreeNode>>()+ var i = blockStart+ while (i < blockEnd) {+ val child = nodes[i]+ if (child.depth == childDepth) {+ var j = i + 1+ while (j < blockEnd && nodes[j].depth > childDepth) j+++ preservedNode[child.entry.documentId] = child+ preservedSubtree[child.entry.documentId] = nodes.subList(i + 1, j).toList()+ i = j+ } else {+ i+++ }+ }++ val entries = withContext(Dispatchers.IO) { SafFiles.listChildren(context, tree, parentDocId) }++ val rebuilt = ArrayList<TreeNode>()+ for (entry in entries) {+ val existing = preservedNode[entry.documentId]+ if (existing != null) {+ rebuilt.add(existing)+ rebuilt.addAll(preservedSubtree[entry.documentId].orEmpty())+ } else {+ rebuilt.add(TreeNode(entry, childDepth))+ }+ }++ for (k in blockEnd - 1 downTo blockStart) nodes.removeAt(k)+ nodes.addAll(blockStart, rebuilt)+ }++ /** Resolves the document id of a create target: the tree root, or a directory row. */+ private fun parentDocId(parentIndex: Int?): String? =+ if (parentIndex == null) rootDocumentId else nodes.getOrNull(parentIndex)?.entry?.documentId++ override fun createFile(parentIndex: Int?, name: String) {+ val tree = treeUri ?: return+ val parentDoc = parentDocId(parentIndex) ?: return+ viewModelScope.launch {+ val uri = withContext(Dispatchers.IO) {+ SafFiles.createDocument(context, tree, parentDoc, name, SafFiles.mimeForFileName(name))+ } ?: return@launch+ nodes.getOrNull(parentIndex ?: -1)?.expanded = true+ refreshChildren(parentIndex)+ openFile(uri, name)+ }+ }++ override fun createFolder(parentIndex: Int?, name: String) {+ val tree = treeUri ?: return+ val parentDoc = parentDocId(parentIndex) ?: return+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ SafFiles.createDocument(+ context, tree, parentDoc, name, DocumentsContract.Document.MIME_TYPE_DIR,+ )+ } ?: return@launch+ nodes.getOrNull(parentIndex ?: -1)?.expanded = true+ refreshChildren(parentIndex)+ }+ }++ override fun renameNode(index: Int, newName: String) {+ val node = nodes.getOrNull(index) ?: return+ val oldUri = node.entry.uri+ viewModelScope.launch {+ val newUri = withContext(Dispatchers.IO) {+ SafFiles.renameDocument(context, oldUri, newName)+ } ?: return@launch+ val newDocId = runCatching { DocumentsContract.getDocumentId(newUri) }+ .getOrDefault(node.entry.documentId)+ val at = nodes.indexOf(node)+ if (at >= 0) {+ // A renamed directory's descendant ids may shift; drop them so a re-expand re-lists.+ if (node.entry.isDirectory) removeDescendants(at)+ val newEntry = node.entry.copy(documentId = newDocId, name = newName, uri = newUri)+ nodes[at] = TreeNode(newEntry, node.depth)+ }+ tabs.firstOrNull { it.uri == oldUri }?.let { tab ->+ tab.uri = newUri+ tab.name = newName+ tab.language = Language.fromFileName(newName)+ }+ }+ }++ override fun deleteNode(index: Int) {+ val node = nodes.getOrNull(index) ?: return+ val uri = node.entry.uri+ viewModelScope.launch {+ val ok = withContext(Dispatchers.IO) { SafFiles.deleteDocument(context, uri) }+ if (!ok) return@launch+ val at = nodes.indexOf(node)+ if (at >= 0) {+ removeDescendants(at)+ nodes.removeAt(at)+ }+ closeTabsUnder(uri)+ }+ }++ /** Closes any open tab whose file is [uri] or lives beneath it (for a deleted directory). */+ private fun closeTabsUnder(uri: Uri) {+ val target = uri.toString()+ for (i in tabs.indices.reversed()) {+ val tabUri = tabs[i].uri.toString()+ if (tabUri == target || tabUri.startsWith("$target%2F") || tabUri.startsWith("$target/")) {+ closeTab(i)+ }+ }+ }+ // ---- Tab handling ---- /** Opens [uri] in a tab (focusing it if already open), reading its text off the main thread. */@@ -253,8 +428,17 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), override fun onEditorChange(new: TextFieldValue) { val tab = currentTab ?: return- if (new.text != tab.value.text) tab.pushUndo(tab.value)- tab.value = new+ val indentUnit = " ".repeat(tabWidth)+ val processed = applyEditorInput(tab.value, new, indentUnit, autoIndent, autoCloseBrackets)+ if (processed.text != tab.value.text) tab.pushUndo(tab.value)+ tab.value = processed+ }++ /** Moves the caret to the start of [line] (1-based), without recording an undo step. */+ override fun goToLine(line: Int) {+ val tab = currentTab ?: return+ val offset = lineStartOffset(tab.value.text, line)+ setSelection(TextRange(offset)) } /** Moves the selection without recording an undo step (used by find navigation). */@@ -297,6 +481,31 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { prefs.setSoftWrap(softWrap) } } + override fun setFontSize(size: Int) {+ fontSize = size+ viewModelScope.launch { prefs.setFontSize(size) }+ }++ override fun setTabWidth(width: Int) {+ tabWidth = width+ viewModelScope.launch { prefs.setTabWidth(width) }+ }++ override fun setThemeMode(mode: String) {+ themeMode = mode+ viewModelScope.launch { prefs.setThemeMode(mode) }+ }++ override fun setAutoIndent(enabled: Boolean) {+ autoIndent = enabled+ viewModelScope.launch { prefs.setAutoIndent(enabled) }+ }++ override fun setAutoCloseBrackets(enabled: Boolean) {+ autoCloseBrackets = enabled+ viewModelScope.launch { prefs.setAutoCloseBrackets(enabled) }+ }+ // ---- Find & replace ---- override fun replaceRange(range: IntRange, replacement: String) {@@ -322,4 +531,98 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), sb.append(text, last, text.length) onEditorChange(TextFieldValue(sb.toString(), TextRange(sb.length))) }++ private fun buildRegex(pattern: String, caseSensitive: Boolean): Regex =+ Regex(pattern, if (caseSensitive) emptySet() else setOf(RegexOption.IGNORE_CASE))++ override fun replaceMatchRegex(range: IntRange, pattern: String, replacement: String, caseSensitive: Boolean) {+ val tab = currentTab ?: return+ val text = tab.value.text+ if (range.first < 0 || range.last + 1 > text.length) return+ val regex = runCatching { buildRegex(pattern, caseSensitive) }.getOrNull() ?: return+ val sub = text.substring(range.first, range.last + 1)+ val replaced = runCatching { regex.replace(sub, replacement) }.getOrNull() ?: return+ replaceRange(range, replaced)+ }++ override fun replaceAllRegex(pattern: String, replacement: String, caseSensitive: Boolean) {+ val tab = currentTab ?: return+ val regex = runCatching { buildRegex(pattern, caseSensitive) }.getOrNull() ?: return+ val text = tab.value.text+ val newText = runCatching { regex.replace(text, replacement) }.getOrNull() ?: return+ if (newText == text) return+ onEditorChange(TextFieldValue(newText, TextRange(newText.length)))+ }++ // ---- Project search ----++ override fun searchProject(query: String, caseSensitive: Boolean, useRegex: Boolean) {+ val tree = treeUri ?: return+ val rootId = rootDocumentId ?: return+ searchJob?.cancel()+ if (query.isBlank()) {+ searchResults.clear()+ isSearching = false+ return+ }+ isSearching = true+ searchResults.clear()+ searchJob = viewModelScope.launch {+ val collected = withContext(Dispatchers.IO) {+ val out = ArrayList<SearchResult>()+ val stack = ArrayDeque<String>()+ stack.addLast(rootId)+ while (stack.isNotEmpty() && out.size < MAX_SEARCH_RESULTS) {+ coroutineContext.ensureActive()+ val dirId = stack.removeLast()+ val children = runCatching {+ SafFiles.listChildren(context, tree, dirId)+ }.getOrDefault(emptyList())+ for (child in children) {+ if (out.size >= MAX_SEARCH_RESULTS) break+ if (child.isDirectory) {+ if (child.name !in SKIP_DIRS) stack.addLast(child.documentId)+ continue+ }+ if (Language.fromFileName(child.name) == Language.PLAINTEXT) continue+ val text = runCatching { SafFiles.readText(context, child.uri) }.getOrNull() ?: continue+ if (text.length > MAX_SEARCH_FILE_SIZE) continue+ val matches = findLineMatches(text, query, caseSensitive, useRegex, MAX_MATCHES_PER_FILE)+ for (m in matches) {+ out.add(SearchResult(child.uri, child.name, m.line, m.preview))+ if (out.size >= MAX_SEARCH_RESULTS) break+ }+ }+ }+ out+ }+ searchResults.clear()+ searchResults.addAll(collected)+ isSearching = false+ }+ }++ override fun openSearchResult(result: SearchResult) {+ val existing = tabs.indexOfFirst { it.uri == result.uri }+ if (existing >= 0) {+ currentIndex = existing+ goToLine(result.line)+ return+ }+ viewModelScope.launch {+ val text = withContext(Dispatchers.IO) {+ runCatching { SafFiles.readText(context, result.uri) }.getOrDefault("")+ }+ tabs.add(OpenTab(result.uri, result.name, text, Language.fromFileName(result.name)))+ currentIndex = tabs.lastIndex+ goToLine(result.line)+ }+ }++ private companion object {+ const val MAX_SEARCH_RESULTS = 500+ const val MAX_MATCHES_PER_FILE = 50+ const val MAX_SEARCH_FILE_SIZE = 500_000+ val SKIP_DIRS = setOf(".git", "node_modules", "build", ".gradle", ".idea")+ } }
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 03414e91ad..eb2d770704 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -9,4 +9,43 @@ <string name="all">All</string> <string name="no_folder_opened">No folder opened</string> <string name="open_a_folder_to_browse_your_project_or">Open a folder to browse your project, or open a single file.</string>+ <string name="new_file">New file</string>+ <string name="new_folder">New folder</string>+ <string name="rename">Rename</string>+ <string name="delete">Delete</string>+ <string name="name">Name</string>+ <string name="create">Create</string>+ <string name="cancel">Cancel</string>+ <string name="more_actions">More actions</string>+ <string name="delete_title">Delete "%1$s"?</string>+ <string name="delete_message">This cannot be undone.</string>+ <string name="settings">Settings</string>+ <string name="appearance">Appearance</string>+ <string name="editor">Editor</string>+ <string name="font_size">Font size</string>+ <string name="tab_width">Tab width</string>+ <string name="theme">Theme</string>+ <string name="theme_system">System</string>+ <string name="theme_light">Light</string>+ <string name="theme_dark">Dark</string>+ <string name="auto_indent">Auto-indent</string>+ <string name="auto_indent_desc">Carry indentation to new lines</string>+ <string name="auto_close_brackets">Auto-close brackets</string>+ <string name="auto_close_brackets_desc">Insert the matching closing bracket or quote</string>+ <string name="soft_wrap">Soft wrap</string>+ <string name="soft_wrap_desc">Wrap long lines instead of scrolling</string>+ <string name="close">Close</string>+ <string name="go_to_line">Go to line</string>+ <string name="line">Line</string>+ <string name="go">Go</string>+ <string name="discard_changes_title">Discard unsaved changes?</string>+ <string name="discard">Discard</string>+ <string name="match_case">Match case</string>+ <string name="use_regex">Regex</string>+ <string name="invalid_regex">Invalid pattern</string>+ <string name="search_in_project">Search in project</string>+ <string name="search">Search</string>+ <string name="searching">Searching\u2026</string>+ <string name="no_results">No results</string>+ <string name="line_number">Line %1$d</string> </resources>