Modern Apps git

← Modern-Apps.git

new app: code

Commit
a4403c8fd3ce128c96a8be1af5e39cd342e688b7
Author
Vayun Mathur <[email protected]>
When
2026-07-30 20:55 UTC (4 months ago)
Parents
e173280

Diff

code/build.gradle.kts
diff --git a/code/build.gradle.kts b/code/build.gradle.ktsnew file mode 100644index 0000000000..ab224f16fe--- /dev/null+++ b/code/build.gradle.kts@@ -0,0 +1,19 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "code"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.code"+    }+}++dependencies {+    implementation(libs.androidx.datastore.preferences)+}
code/src/main/AndroidManifest.xml
diff --git a/code/src/main/AndroidManifest.xml b/code/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..c3324837a6--- /dev/null+++ b/code/src/main/AndroidManifest.xml@@ -0,0 +1,31 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+            <!-- Open text files shared/viewed from other apps directly in the editor. -->+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <action android:name="android.intent.action.EDIT" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="text/*" />+            </intent-filter>+        </activity>+    </application>++</manifest>
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.ktnew file mode 100644index 0000000000..61d54ec354--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/MainActivity.kt@@ -0,0 +1,58 @@+package com.vayunmathur.code++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.code.ui.EditorScreen+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.rememberNavBackStack+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+    private val viewModel: EditorViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        handleIntent(intent)+        setContent {+            DynamicTheme {+                Navigation(viewModel)+            }+        }+    }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        handleIntent(intent)+    }++    /** VIEW/EDIT opens from other apps carry the file in [Intent.getData]; open it in a tab. */+    private fun handleIntent(intent: Intent?) {+        intent ?: return+        if (intent.action == Intent.ACTION_VIEW || intent.action == Intent.ACTION_EDIT) {+            intent.data?.let { viewModel.openExternal(it) }+        }+    }+}++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Editor : Route+}++@Composable+fun Navigation(viewModel: EditorViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Editor)+    MainNavigation(backStack) {+        entry<Route.Editor> { EditorScreen(viewModel) }+    }+}
code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt
diff --git a/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.ktnew file mode 100644index 0000000000..4382025288--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/syntax/SyntaxHighlighting.kt@@ -0,0 +1,310 @@+package com.vayunmathur.code.syntax++import androidx.compose.runtime.Composable+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.input.OffsetMapping+import androidx.compose.ui.text.input.TransformedText+import androidx.compose.ui.text.input.VisualTransformation+import com.vayunmathur.library.ui.MaterialTheme++/**+ * Self-contained, regex-driven syntax highlighting.+ *+ * Each [Language] compiles once into a single alternation [Regex] whose top-level+ * alternatives are capturing groups (internally everything uses non-capturing groups so+ * group indices map 1:1 to [TokenKind]s). Highlighting is then a single left-to-right+ * `findAll` pass — because regex alternation is ordered and scanning resumes past each+ * match, comments/strings naturally "swallow" any keywords or numbers inside them.+ *+ * Colors are resolved from the Material color scheme at draw time (via [SyntaxColors]) so+ * the same tokenization looks correct in both light and dark themes.+ */+enum class TokenKind { COMMENT, STRING, NUMBER, ANNOTATION, KEYWORD }++/** Precompiled tokenizer for one language: the alternation regex + per-group kinds. */+class LanguageSpec(private val parts: List<Pair<TokenKind, String>>) {+    private val kinds: List<TokenKind> = parts.map { it.first }+    val regex: Regex = Regex(+        parts.joinToString("|") { "(${it.second})" },+        setOf(RegexOption.MULTILINE),+    )++    /** Which token a match belongs to, found by the first non-null capturing group. */+    fun kindFor(match: MatchResult): TokenKind? {+        for (i in kinds.indices) {+            if (match.groups[i + 1] != null) return kinds[i]+        }+        return null+    }+}++enum class Language(val label: String) {+    KOTLIN("Kotlin"),+    JAVA("Java"),+    JAVASCRIPT("JavaScript"),+    TYPESCRIPT("TypeScript"),+    PYTHON("Python"),+    C("C"),+    CPP("C++"),+    RUST("Rust"),+    JSON("JSON"),+    XML("XML"),+    MARKDOWN("Markdown"),+    PLAINTEXT("Plain Text");++    /** The tokenizer for this language, or null for languages we render without colors. */+    val spec: LanguageSpec? by lazy { specFor(this) }++    companion object {+        /** Picks a language from a file name's extension, defaulting to plain text. */+        fun fromFileName(name: String): Language {+            val ext = name.substringAfterLast('.', "").lowercase()+            return when (ext) {+                "kt", "kts" -> KOTLIN+                "java" -> JAVA+                "js", "jsx", "mjs", "cjs" -> JAVASCRIPT+                "ts", "tsx" -> TYPESCRIPT+                "py", "pyw" -> PYTHON+                "c", "h" -> C+                "cpp", "cc", "cxx", "hpp", "hh", "hxx" -> CPP+                "rs" -> RUST+                "json" -> JSON+                "xml", "html", "htm", "svg", "xhtml" -> XML+                "md", "markdown" -> MARKDOWN+                else -> PLAINTEXT+            }+        }+    }+}++// --- Reusable regex fragments (only non-capturing groups inside each) ---+private const val DOUBLE_STRING = "\"(?:\\\\.|[^\"\\\\\\n])*\""+private const val SINGLE_STRING = "'(?:\\\\.|[^'\\\\\\n])*'"+private const val BACKTICK_STRING = "`(?:\\\\.|[^`\\\\])*`"+private const val TRIPLE_DOUBLE = "\"\"\"[\\s\\S]*?\"\"\""+private const val TRIPLE_SINGLE = "'''[\\s\\S]*?'''"+private const val LINE_COMMENT = "//[^\\n]*"+private const val BLOCK_COMMENT = "/\\*[\\s\\S]*?\\*/"+private const val HASH_COMMENT = "#[^\\n]*"+private const val NUMBER = "\\b(?:0[xX][0-9a-fA-F_]+|\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[eE][+-]?\\d+)?[fFlLuU]*)\\b"+private const val ANNOTATION = "@\\w+"++private fun keywords(vararg words: String) = "\\b(?:" + words.joinToString("|") + ")\\b"++private fun specFor(language: Language): LanguageSpec? = when (language) {+    Language.KOTLIN, Language.JAVA -> LanguageSpec(+        listOf(+            TokenKind.COMMENT to BLOCK_COMMENT,+            TokenKind.COMMENT to LINE_COMMENT,+            TokenKind.STRING to TRIPLE_DOUBLE,+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.STRING to SINGLE_STRING,+            TokenKind.ANNOTATION to ANNOTATION,+            TokenKind.KEYWORD to keywords(+                "abstract", "as", "assert", "boolean", "break", "byte", "case", "catch", "char",+                "class", "companion", "const", "constructor", "continue", "crossinline", "data",+                "default", "do", "double", "dynamic", "else", "enum", "extends", "external",+                "false", "final", "finally", "float", "for", "fun", "get", "goto", "if",+                "implements", "import", "in", "infix", "init", "inline", "inner", "instanceof",+                "int", "interface", "internal", "is", "lateinit", "lazy", "long", "native", "new",+                "null", "object", "open", "operator", "out", "override", "package", "private",+                "protected", "public", "reified", "return", "sealed", "set", "short", "static",+                "strictfp", "super", "suspend", "switch", "synchronized", "tailrec", "this",+                "throw", "throws", "transient", "true", "try", "typealias", "val", "var", "vararg",+                "void", "volatile", "when", "where", "while",+            ),+            TokenKind.NUMBER to NUMBER,+        )+    )++    Language.JAVASCRIPT, Language.TYPESCRIPT -> LanguageSpec(+        listOf(+            TokenKind.COMMENT to BLOCK_COMMENT,+            TokenKind.COMMENT to LINE_COMMENT,+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.STRING to SINGLE_STRING,+            TokenKind.STRING to BACKTICK_STRING,+            TokenKind.KEYWORD to keywords(+                "abstract", "any", "as", "async", "await", "boolean", "break", "case", "catch",+                "class", "const", "continue", "debugger", "declare", "default", "delete", "do",+                "else", "enum", "export", "extends", "false", "finally", "for", "from", "function",+                "get", "if", "implements", "import", "in", "instanceof", "interface", "let",+                "namespace", "never", "new", "null", "number", "object", "of", "package", "private",+                "protected", "public", "readonly", "return", "set", "static", "string", "super",+                "switch", "this", "throw", "true", "try", "type", "typeof", "undefined", "var",+                "void", "while", "with", "yield",+            ),+            TokenKind.NUMBER to NUMBER,+        )+    )++    Language.PYTHON -> LanguageSpec(+        listOf(+            TokenKind.STRING to TRIPLE_DOUBLE,+            TokenKind.STRING to TRIPLE_SINGLE,+            TokenKind.COMMENT to HASH_COMMENT,+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.STRING to SINGLE_STRING,+            TokenKind.ANNOTATION to ANNOTATION,+            TokenKind.KEYWORD to keywords(+                "False", "None", "True", "and", "as", "assert", "async", "await", "break", "case",+                "class", "continue", "def", "del", "elif", "else", "except", "finally", "for",+                "from", "global", "if", "import", "in", "is", "lambda", "match", "nonlocal", "not",+                "or", "pass", "raise", "return", "self", "try", "while", "with", "yield",+            ),+            TokenKind.NUMBER to NUMBER,+        )+    )++    Language.C, Language.CPP -> LanguageSpec(+        listOf(+            TokenKind.COMMENT to BLOCK_COMMENT,+            TokenKind.COMMENT to LINE_COMMENT,+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.STRING to SINGLE_STRING,+            TokenKind.ANNOTATION to "^\\s*#\\s*\\w+", // preprocessor directives+            TokenKind.KEYWORD to keywords(+                "alignas", "alignof", "and", "asm", "auto", "bool", "break", "case", "catch",+                "char", "class", "const", "constexpr", "const_cast", "continue", "decltype",+                "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit",+                "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline",+                "int", "long", "mutable", "namespace", "new", "noexcept", "nullptr", "operator",+                "private", "protected", "public", "register", "reinterpret_cast", "return", "short",+                "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch",+                "template", "this", "throw", "true", "try", "typedef", "typeid", "typename",+                "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while",+            ),+            TokenKind.NUMBER to NUMBER,+        )+    )++    Language.RUST -> LanguageSpec(+        listOf(+            TokenKind.COMMENT to BLOCK_COMMENT,+            TokenKind.COMMENT to LINE_COMMENT,+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.ANNOTATION to "#!?\\[[^\\]]*\\]", // attributes like #[derive(...)]+            TokenKind.KEYWORD to keywords(+                "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else",+                "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match",+                "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct",+                "super", "trait", "true", "type", "unsafe", "use", "where", "while",+            ),+            TokenKind.NUMBER to NUMBER,+        )+    )++    Language.JSON -> LanguageSpec(+        listOf(+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.KEYWORD to keywords("true", "false", "null"),+            TokenKind.NUMBER to NUMBER,+        )+    )++    Language.XML -> LanguageSpec(+        listOf(+            TokenKind.COMMENT to "<!--[\\s\\S]*?-->",+            TokenKind.STRING to DOUBLE_STRING,+            TokenKind.STRING to SINGLE_STRING,+            TokenKind.KEYWORD to "</?[?!]?[A-Za-z][\\w:.-]*|/?>",+            TokenKind.NUMBER to "&#?\\w+;", // entities+        )+    )++    Language.MARKDOWN -> LanguageSpec(+        listOf(+            TokenKind.STRING to "```[\\s\\S]*?```",+            TokenKind.STRING to "`[^`\\n]+`",+            TokenKind.KEYWORD to "^#{1,6} .*$",+            TokenKind.NUMBER to "\\[[^\\]\\n]*\\]\\([^)\\n]*\\)", // links+            TokenKind.ANNOTATION to "\\*\\*[^*\\n]+\\*\\*|__[^_\\n]+__", // bold+            TokenKind.ANNOTATION to "\\*[^*\\n]+\\*|_[^_\\n]+_",       // italic+            TokenKind.COMMENT to "^>.*$", // blockquote+        )+    )++    Language.PLAINTEXT -> null+}++/** Theme-derived colors for each token kind plus find-match highlights. */+data class SyntaxColors(+    val keyword: Color,+    val string: Color,+    val number: Color,+    val comment: Color,+    val annotation: Color,+    val match: Color,+    val activeMatch: Color,+) {+    fun colorFor(kind: TokenKind): Color = when (kind) {+        TokenKind.COMMENT -> comment+        TokenKind.STRING -> string+        TokenKind.NUMBER -> number+        TokenKind.ANNOTATION -> annotation+        TokenKind.KEYWORD -> keyword+    }+}++@Composable+fun rememberSyntaxColors(): SyntaxColors {+    val scheme = MaterialTheme.colorScheme+    return SyntaxColors(+        keyword = scheme.primary,+        string = scheme.tertiary,+        number = scheme.secondary,+        comment = scheme.onSurfaceVariant,+        annotation = scheme.error,+        match = scheme.primary.copy(alpha = 0.30f),+        activeMatch = scheme.tertiary.copy(alpha = 0.55f),+    )+}++/**+ * A [VisualTransformation] that leaves the text unchanged (identity offset mapping) but+ * layers syntax spans and find-match backgrounds onto it. Highlighting is skipped for+ * very large documents to keep typing responsive.+ */+class SyntaxTransformation(+    private val spec: LanguageSpec?,+    private val colors: SyntaxColors,+    private val matches: List<IntRange> = emptyList(),+    private val activeMatch: Int = -1,+) : VisualTransformation {++    override fun filter(text: AnnotatedString): TransformedText {+        val raw = text.text+        val builder = AnnotatedString.Builder(text)++        if (spec != null && raw.length <= MAX_HIGHLIGHT_LENGTH) {+            for (match in spec.regex.findAll(raw)) {+                val kind = spec.kindFor(match) ?: continue+                builder.addStyle(+                    SpanStyle(color = colors.colorFor(kind)),+                    match.range.first,+                    match.range.last + 1,+                )+            }+        }++        matches.forEachIndexed { index, range ->+            if (range.isEmpty()) return@forEachIndexed+            val background = if (index == activeMatch) colors.activeMatch else colors.match+            builder.addStyle(+                SpanStyle(background = background),+                range.first.coerceIn(0, raw.length),+                (range.last + 1).coerceIn(0, raw.length),+            )+        }++        return TransformedText(builder.toAnnotatedString(), OffsetMapping.Identity)+    }++    private companion object {+        // Above this size, skip tokenization: a single regex pass over hundreds of KB per+        // keystroke would jank. The file still opens and edits fine, just uncolored.+        const val MAX_HIGHLIGHT_LENGTH = 150_000+    }+}
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.ktnew file mode 100644index 0000000000..7fdf2b1da8--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditor.kt@@ -0,0 +1,225 @@+package com.vayunmathur.code.ui++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+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.verticalScroll+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.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.code.syntax.SyntaxTransformation+import com.vayunmathur.code.syntax.rememberSyntaxColors+import com.vayunmathur.code.util.EditorViewModel+import com.vayunmathur.code.util.OpenTab+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconChevronRight+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconKeyboardArrowUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * The editing surface: an optional find/replace bar above a scroll-synced line-number gutter+ * and a monospace [BasicTextField]. Syntax highlighting and match highlighting are applied+ * through a [SyntaxTransformation]; horizontal scrolling is enabled only when soft-wrap is off.+ */+@Composable+fun CodeEditor(+    viewModel: EditorViewModel,+    tab: OpenTab,+    softWrap: Boolean,+    showFind: Boolean,+    onCloseFind: () -> Unit,+    modifier: Modifier = Modifier,+) {+    // Find/replace state is per-tab, so it resets when switching files.+    var query by remember(tab) { mutableStateOf("") }+    var replacement by remember(tab) { mutableStateOf("") }+    var caseSensitive by remember(tab) { mutableStateOf(false) }+    var activeMatch by remember(tab) { mutableStateOf(0) }++    val text = tab.value.text+    val matches = remember(text, query, caseSensitive) {+        if (query.isEmpty()) {+            emptyList()+        } else {+            val found = ArrayList<IntRange>()+            var i = text.indexOf(query, 0, ignoreCase = !caseSensitive)+            while (i >= 0) {+                found.add(i until i + query.length)+                i = text.indexOf(query, i + query.length, ignoreCase = !caseSensitive)+            }+            found+        }+    }++    LaunchedEffect(matches.size) {+        if (activeMatch >= matches.size) activeMatch = 0+    }++    val goTo: (Int) -> Unit = { target ->+        if (matches.isNotEmpty()) {+            val idx = ((target % matches.size) + matches.size) % matches.size+            activeMatch = idx+            val range = matches[idx]+            viewModel.setSelection(TextRange(range.first, range.last + 1))+        }+    }++    Column(modifier.fillMaxSize()) {+        if (showFind) {+            FindBar(+                query = query,+                replacement = replacement,+                caseSensitive = caseSensitive,+                matchCount = matches.size,+                activeMatch = activeMatch,+                onQueryChange = { query = it; activeMatch = 0 },+                onReplacementChange = { replacement = it },+                onToggleCase = { caseSensitive = !caseSensitive },+                onNext = { goTo(activeMatch + 1) },+                onPrev = { goTo(activeMatch - 1) },+                onReplace = {+                    if (matches.isNotEmpty()) {+                        viewModel.replaceRange(matches[activeMatch], replacement)+                    }+                },+                onReplaceAll = { viewModel.replaceAll(matches, replacement) },+                onClose = onCloseFind,+            )+            HorizontalDivider()+        }++        val editorStyle = TextStyle(+            fontFamily = FontFamily.Monospace,+            fontSize = 14.sp,+            lineHeight = 20.sp,+            color = MaterialTheme.colorScheme.onSurface,+        )+        val syntaxColors = rememberSyntaxColors()+        val highlightMatches = if (showFind) matches else emptyList()+        val transformation = remember(tab.language, syntaxColors, highlightMatches, activeMatch) {+            SyntaxTransformation(tab.language.spec, syntaxColors, highlightMatches, activeMatch)+        }++        val verticalScroll = rememberScrollState()+        val horizontalScroll = rememberScrollState()+        val lineCount = remember(text) { text.count { it == '\n' } + 1 }++        Row(Modifier.fillMaxSize()) {+            LineGutter(lineCount, verticalScroll, editorStyle)+            BasicTextField(+                value = tab.value,+                onValueChange = viewModel::onEditorChange,+                modifier = Modifier+                    .weight(1f)+                    .fillMaxHeight()+                    .verticalScroll(verticalScroll)+                    .then(if (softWrap) Modifier else Modifier.horizontalScroll(horizontalScroll))+                    .padding(horizontal = 8.dp),+                textStyle = editorStyle,+                cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),+                visualTransformation = transformation,+            )+        }+    }+}++/**+ * The line-number column. Rendered as a single right-aligned [Text] (one number per line) so+ * it stays cheap for large files, and sharing [verticalScroll] keeps it locked to the editor.+ * With soft-wrap on, wrapped lines shift the text below their number — an accepted trade-off.+ */+@Composable+private fun LineGutter(lineCount: Int, verticalScroll: androidx.compose.foundation.ScrollState, style: TextStyle) {+    val numbers = remember(lineCount) { (1..lineCount).joinToString("\n") }+    val width = (lineCount.toString().length * 10 + 16).dp+    Text(+        text = numbers,+        modifier = Modifier+            .verticalScroll(verticalScroll)+            .width(width)+            .padding(horizontal = 4.dp),+        style = style,+        color = MaterialTheme.colorScheme.onSurfaceVariant,+        textAlign = TextAlign.Right,+    )+}++/** The find/replace bar: two fields, prev/next navigation, a match count and replace actions. */+@Composable+private fun FindBar(+    query: String,+    replacement: String,+    caseSensitive: Boolean,+    matchCount: Int,+    activeMatch: Int,+    onQueryChange: (String) -> Unit,+    onReplacementChange: (String) -> Unit,+    onToggleCase: () -> Unit,+    onNext: () -> Unit,+    onPrev: () -> Unit,+    onReplace: () -> Unit,+    onReplaceAll: () -> Unit,+    onClose: () -> Unit,+) {+    Column(Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp)) {+        Row(verticalAlignment = Alignment.CenterVertically) {+            OutlinedTextField(+                value = query,+                onValueChange = onQueryChange,+                modifier = Modifier.weight(1f),+                placeholder = { Text("Find") },+                singleLine = true,+            )+            val label = if (matchCount == 0) "0/0" else "${activeMatch + 1}/$matchCount"+            Text(label, modifier = Modifier.padding(horizontal = 8.dp))+            IconButton(onClick = onPrev, enabled = matchCount > 0) { IconKeyboardArrowUp() }+            IconButton(onClick = onNext, enabled = matchCount > 0) { IconChevronRight() }+            IconButton(onClick = onClose) { IconClose() }+        }+        Spacer(Modifier.size(4.dp))+        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+            OutlinedTextField(+                value = replacement,+                onValueChange = onReplacementChange,+                modifier = Modifier.weight(1f),+                placeholder = { Text("Replace") },+                singleLine = true,+            )+            TextButton(onClick = onReplace, enabled = matchCount > 0) { Text("Replace") }+            TextButton(onClick = onReplaceAll, enabled = matchCount > 0) { Text("All") }+        }+        Box {+            TextButton(onClick = onToggleCase) {+                Text(if (caseSensitive) "Case: On" else "Case: Off")+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..435f100a45--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -0,0 +1,213 @@+package com.vayunmathur.code.ui++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+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+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+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.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.code.util.EditorViewModel+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+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.IconRedo+import com.vayunmathur.library.ui.IconSave+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.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.rememberDrawerState+import kotlinx.coroutines.launch++/**+ * Top-level editor scaffold: a navigation drawer holding the [FileTreePane], a top bar to+ * open it, then a tab strip, toolbar, optional find bar and the [CodeEditor] itself. The+ * folder/file pickers use the Storage Access Framework so no storage permissions are needed.+ */+@Composable+fun EditorScreen(viewModel: EditorViewModel) {+    val drawerState = rememberDrawerState(DrawerValue.Closed)+    val scope = rememberCoroutineScope()++    val folderLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.OpenDocumentTree()+    ) { uri -> uri?.let(viewModel::openFolder) }++    val fileLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.OpenDocument()+    ) { uri -> uri?.let(viewModel::openExternal) }++    ModalNavigationDrawer(+        drawerState = drawerState,+        drawerContent = {+            ModalDrawerSheet {+                FileTreePane(+                    viewModel = viewModel,+                    onOpenFolder = { folderLauncher.launch(null) },+                    onOpenFile = { fileLauncher.launch(arrayOf("*/*")) },+                    onFileOpened = { scope.launch { drawerState.close() } },+                )+            }+        },+    ) {+        Scaffold(+            topBar = {+                TopAppBar(+                    title = { Text(viewModel.currentTab?.name ?: "Code") },+                    navigationIcon = {+                        IconButton(onClick = { scope.launch { drawerState.open() } }) { IconMenu() }+                    },+                )+            },+        ) { padding ->+            Column(Modifier.fillMaxSize().padding(padding)) {+                val tab = viewModel.currentTab+                if (tab == null) {+                    EmptyEditorState(+                        onOpenFolder = { folderLauncher.launch(null) },+                        onOpenFile = { fileLauncher.launch(arrayOf("*/*")) },+                    )+                } else {+                    TabStrip(viewModel)+                    HorizontalDivider()+                    var showFind by remember { mutableStateOf(false) }+                    EditorToolbar(viewModel = viewModel, onToggleFind = { showFind = !showFind })+                    HorizontalDivider()+                    CodeEditor(+                        viewModel = viewModel,+                        tab = tab,+                        softWrap = viewModel.softWrap,+                        showFind = showFind,+                        onCloseFind = { showFind = false },+                        modifier = Modifier.weight(1f),+                    )+                }+            }+        }+    }+}++/** Shown when nothing is open: prompts the user to open a folder or a single file. */+@Composable+private fun EmptyEditorState(onOpenFolder: () -> Unit, onOpenFile: () -> Unit) {+    Column(+        modifier = Modifier.fillMaxSize().padding(24.dp),+        verticalArrangement = Arrangement.Center,+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        IconCode(Modifier.size(64.dp), tint = MaterialTheme.colorScheme.primary)+        Spacer(Modifier.size(16.dp))+        Text("No file open", style = MaterialTheme.typography.titleLarge)+        Spacer(Modifier.size(8.dp))+        Text(+            "Open a folder to browse your project, or open a single file.",+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Spacer(Modifier.size(16.dp))+        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+            Button(onClick = onOpenFolder) { Text("Open folder") }+            Button(onClick = onOpenFile) { Text("Open file") }+        }+    }+}++/** Horizontally scrollable strip of open tabs, each with a dirty indicator and close button. */+@Composable+private fun TabStrip(viewModel: EditorViewModel) {+    Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {+        viewModel.tabs.forEachIndexed { index, tab ->+            val selected = index == viewModel.currentIndex+            val background =+                if (selected) MaterialTheme.colorScheme.surfaceVariant else Color.Transparent+            Row(+                modifier = Modifier+                    .background(background)+                    .clickable { viewModel.selectTab(index) }+                    .padding(start = 12.dp),+                verticalAlignment = Alignment.CenterVertically,+            ) {+                Text(+                    text = tab.name,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                    color = if (selected) MaterialTheme.colorScheme.onSurface+                    else MaterialTheme.colorScheme.onSurfaceVariant,+                )+                Spacer(Modifier.width(6.dp))+                if (tab.isDirty) {+                    Box(+                        Modifier+                            .size(8.dp)+                            .clip(CircleShape)+                            .background(MaterialTheme.colorScheme.primary)+                    )+                }+                IconButton(onClick = { viewModel.closeTab(tab) }, modifier = Modifier.size(32.dp)) {+                    IconClose(Modifier.size(16.dp))+                }+            }+        }+    }+}++/** Undo/redo, save, find, soft-wrap, tab-insert and a language indicator. */+@Composable+private fun EditorToolbar(viewModel: EditorViewModel, onToggleFind: () -> Unit) {+    val tab = viewModel.currentTab ?: return+    Row(+        modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        IconButton(onClick = { viewModel.undo() }, enabled = tab.canUndo) { IconUndo() }+        IconButton(onClick = { viewModel.redo() }, enabled = tab.canRedo) { IconRedo() }+        IconButton(onClick = { viewModel.save() }, enabled = tab.isDirty) { IconSave() }+        IconButton(onClick = onToggleFind) { IconFindReplace() }+        IconButton(onClick = { viewModel.toggleSoftWrap() }) {+            IconWrapText(+                tint = if (viewModel.softWrap) MaterialTheme.colorScheme.primary+                else MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        IconButton(onClick = { viewModel.insertText("    ") }) { IconFormatIndentIncrease() }+        Spacer(Modifier.width(8.dp))+        Text(+            text = tab.language.label,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            style = MaterialTheme.typography.labelMedium,+            modifier = Modifier.padding(horizontal = 12.dp),+        )+    }+}
code/src/main/java/com/vayunmathur/code/ui/FileTreePane.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/FileTreePane.kt b/code/src/main/java/com/vayunmathur/code/ui/FileTreePane.ktnew file mode 100644index 0000000000..c3a2bfbf81--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/FileTreePane.kt@@ -0,0 +1,119 @@+package com.vayunmathur.code.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.code.util.EditorViewModel+import com.vayunmathur.code.util.TreeNode+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconChevronRight+import com.vayunmathur.library.ui.IconFile+import com.vayunmathur.library.ui.IconFolder+import com.vayunmathur.library.ui.IconFolderOpen+import com.vayunmathur.library.ui.IconKeyboardArrowDown+import com.vayunmathur.library.ui.IconNewFile+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/**+ * The drawer's file browser: a header with folder actions and a lazily-built, flat file tree.+ * Tapping a directory expands/collapses it; tapping a file opens it (and the caller closes+ * the drawer). Shows an "open folder" empty state until a folder has been chosen.+ */+@Composable+fun FileTreePane(+    viewModel: EditorViewModel,+    onOpenFolder: () -> Unit,+    onOpenFile: () -> Unit,+    onFileOpened: () -> Unit,+) {+    Column(Modifier.fillMaxSize()) {+        Row(+            modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp, top = 8.dp, bottom = 8.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            Text(+                text = viewModel.rootName ?: "Explorer",+                modifier = Modifier.weight(1f),+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+                style = MaterialTheme.typography.titleMedium,+            )+            IconButton(onClick = onOpenFile) { IconNewFile() }+            IconButton(onClick = onOpenFolder) { IconFolderOpen() }+        }+        HorizontalDivider()++        if (viewModel.treeUri == null) {+            Column(+                modifier = Modifier.fillMaxSize().padding(24.dp),+                verticalArrangement = Arrangement.Center,+                horizontalAlignment = Alignment.CenterHorizontally,+            ) {+                IconFolder(Modifier.size(48.dp))+                Spacer(Modifier.size(12.dp))+                Text(+                    "No folder opened",+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                Spacer(Modifier.size(12.dp))+                Button(onClick = onOpenFolder) { Text("Open folder") }+            }+        } else {+            LazyColumn(Modifier.fillMaxSize()) {+                items(viewModel.nodes, key = { it.entry.uri.toString() }) { node ->+                    TreeRow(node) {+                        val wasFile = !node.entry.isDirectory+                        viewModel.toggle(node)+                        if (wasFile) onFileOpened()+                    }+                }+            }+        }+    }+}++@Composable+private fun TreeRow(node: TreeNode, onClick: () -> Unit) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .clickable(onClick = onClick)+            .padding(start = (node.depth * 16 + 8).dp, end = 8.dp, top = 6.dp, bottom = 6.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        if (node.entry.isDirectory) {+            if (node.expanded) IconKeyboardArrowDown(Modifier.size(20.dp)) else IconChevronRight(Modifier.size(20.dp))+        } else {+            Spacer(Modifier.width(20.dp))+        }+        Spacer(Modifier.width(4.dp))+        when {+            node.entry.isDirectory && node.expanded -> IconFolderOpen(Modifier.size(20.dp))+            node.entry.isDirectory -> IconFolder(Modifier.size(20.dp))+            else -> IconFile(Modifier.size(20.dp))+        }+        Spacer(Modifier.width(8.dp))+        Text(+            text = node.entry.name,+            maxLines = 1,+            overflow = TextOverflow.Ellipsis,+        )+    }+}
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.ktnew file mode 100644index 0000000000..9bf831521d--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -0,0 +1,42 @@+package com.vayunmathur.code.util++import android.content.Context+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.booleanPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.editorDataStore: DataStore<Preferences> by preferencesDataStore(name = "code_editor")++/**+ * Persists the small amount of state that should survive relaunches: the last opened+ * folder tree (so the file browser reopens where it was) and the soft-wrap toggle.+ */+class EditorPrefs(context: Context) {++    private val appContext = context.applicationContext++    val folderUri: Flow<String?> = appContext.editorDataStore.data.map { it[FOLDER_URI_KEY] }+    val softWrap: Flow<Boolean> = appContext.editorDataStore.data.map { it[SOFT_WRAP_KEY] ?: false }++    suspend fun setFolderUri(uri: String) {+        appContext.editorDataStore.edit { it[FOLDER_URI_KEY] = uri }+    }++    suspend fun clearFolderUri() {+        appContext.editorDataStore.edit { it.remove(FOLDER_URI_KEY) }+    }++    suspend fun setSoftWrap(enabled: Boolean) {+        appContext.editorDataStore.edit { it[SOFT_WRAP_KEY] = enabled }+    }++    private companion object {+        val FOLDER_URI_KEY = stringPreferencesKey("folder_uri")+        val SOFT_WRAP_KEY = booleanPreferencesKey("soft_wrap")+    }+}
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.ktnew file mode 100644index 0000000000..a59f415849--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -0,0 +1,292 @@+package com.vayunmathur.code.util++import android.app.Application+import android.content.Intent+import android.net.Uri+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.code.syntax.Language+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** 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) {+    var expanded by mutableStateOf(false)+    var loading by mutableStateOf(false)+}++/**+ * One open file. Editor content lives in [value]; [savedText] is the last persisted text so+ * [isDirty] can drive the unsaved-dot. Undo/redo are plain deques (not observed directly);+ * [canUndo]/[canRedo] mirror their emptiness as state so the toolbar buttons stay reactive.+ */+class OpenTab(+    val uri: Uri,+    initialName: String,+    initialText: String,+    val language: Language,+) {+    var name by mutableStateOf(initialName)+    var value by mutableStateOf(TextFieldValue(initialText))+    var savedText by mutableStateOf(initialText)+    var canUndo by mutableStateOf(false)+        private set+    var canRedo by mutableStateOf(false)+        private set++    private val undoStack = ArrayDeque<TextFieldValue>()+    private val redoStack = ArrayDeque<TextFieldValue>()++    val isDirty: Boolean get() = value.text != savedText++    fun pushUndo(previous: TextFieldValue) {+        undoStack.addLast(previous)+        if (undoStack.size > UNDO_LIMIT) undoStack.removeFirst()+        redoStack.clear()+        canUndo = true+        canRedo = false+    }++    fun undo() {+        val previous = undoStack.removeLastOrNull() ?: return+        redoStack.addLast(value)+        value = previous+        canUndo = undoStack.isNotEmpty()+        canRedo = true+    }++    fun redo() {+        val next = redoStack.removeLastOrNull() ?: return+        undoStack.addLast(value)+        value = next+        canRedo = redoStack.isNotEmpty()+        canUndo = true+    }++    private companion object {+        const val UNDO_LIMIT = 100+    }+}++/**+ * Activity-scoped state for the editor: the open folder tree, the set of open tabs and the+ * editor preferences. An [AndroidViewModel] (obtained via `by viewModels()`) so it can reach+ * the ContentResolver and DataStore through the application context. Compose reads the+ * `mutableStateOf`/`mutableStateListOf` members directly.+ */+class EditorViewModel(application: Application) : AndroidViewModel(application) {++    private val context get() = getApplication<Application>()+    private val prefs = EditorPrefs(context)++    // ---- File tree ----+    var treeUri by mutableStateOf<Uri?>(null)+        private set+    var rootName by mutableStateOf<String?>(null)+        private set+    val nodes = mutableStateListOf<TreeNode>()++    // ---- Tabs ----+    val tabs = mutableStateListOf<OpenTab>()+    var currentIndex by mutableStateOf(-1)+        private set+    val currentTab: OpenTab? get() = tabs.getOrNull(currentIndex)++    // ---- Preferences ----+    var softWrap by mutableStateOf(false)+        private set++    init {+        viewModelScope.launch { softWrap = prefs.softWrap.first() }+        viewModelScope.launch {+            val stored = prefs.folderUri.first() ?: return@launch+            val uri = Uri.parse(stored)+            val loaded = runCatching { loadFolder(uri) }.isSuccess+            if (!loaded) prefs.clearFolderUri()+        }+    }++    // ---- Folder handling ----++    /** Persists read/write access to a freshly picked tree and loads its top level. */+    fun openFolder(uri: Uri) {+        val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+        runCatching { context.contentResolver.takePersistableUriPermission(uri, flags) }+        viewModelScope.launch {+            prefs.setFolderUri(uri.toString())+            loadFolder(uri)+        }+    }++    fun closeFolder() {+        treeUri = null+        rootName = null+        nodes.clear()+        viewModelScope.launch { prefs.clearFolderUri() }+    }++    private suspend fun loadFolder(uri: Uri) {+        val root = withContext(Dispatchers.IO) { SafFiles.rootEntry(context, uri) }+        val children = withContext(Dispatchers.IO) { SafFiles.listChildren(context, uri, root.documentId) }+        treeUri = uri+        rootName = root.name+        nodes.clear()+        nodes.addAll(children.map { TreeNode(it, depth = 0) })+    }++    /** Expands/collapses a directory row, or opens a file row in a tab. */+    fun toggle(node: TreeNode) {+        if (!node.entry.isDirectory) {+            openFile(node.entry.uri, node.entry.name)+            return+        }+        val tree = treeUri ?: return+        val index = nodes.indexOf(node)+        if (index < 0) return++        if (node.expanded) {+            node.expanded = false+            while (index + 1 < nodes.size && nodes[index + 1].depth > node.depth) {+                nodes.removeAt(index + 1)+            }+        } else {+            node.expanded = true+            node.loading = true+            viewModelScope.launch {+                val children = withContext(Dispatchers.IO) {+                    SafFiles.listChildren(context, tree, node.entry.documentId)+                }+                node.loading = false+                // The row may have been collapsed again while loading; only insert if still open.+                val at = nodes.indexOf(node)+                if (at >= 0 && node.expanded) {+                    nodes.addAll(at + 1, children.map { TreeNode(it, node.depth + 1) })+                }+            }+        }+    }++    // ---- Tab handling ----++    /** Opens [uri] in a tab (focusing it if already open), reading its text off the main thread. */+    fun openFile(uri: Uri, name: String? = null) {+        val existing = tabs.indexOfFirst { it.uri == uri }+        if (existing >= 0) {+            currentIndex = existing+            return+        }+        viewModelScope.launch {+            val displayName = name+                ?: withContext(Dispatchers.IO) { SafFiles.queryDisplayName(context, uri) }+                ?: "untitled"+            val text = withContext(Dispatchers.IO) {+                runCatching { SafFiles.readText(context, uri) }.getOrDefault("")+            }+            tabs.add(OpenTab(uri, displayName, text, Language.fromFileName(displayName)))+            currentIndex = tabs.lastIndex+        }+    }++    /** Handles a VIEW/EDIT intent that carries a single file URI. */+    fun openExternal(uri: Uri) {+        runCatching {+            context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)+        }+        openFile(uri)+    }++    fun selectTab(index: Int) {+        if (index in tabs.indices) currentIndex = index+    }++    fun closeTab(tab: OpenTab) {+        val index = tabs.indexOf(tab)+        if (index < 0) return+        val removingCurrent = index == currentIndex+        tabs.removeAt(index)+        currentIndex = when {+            tabs.isEmpty() -> -1+            index < currentIndex -> currentIndex - 1+            removingCurrent -> index.coerceAtMost(tabs.lastIndex)+            else -> currentIndex+        }+    }++    // ---- Editing ----++    fun onEditorChange(new: TextFieldValue) {+        val tab = currentTab ?: return+        if (new.text != tab.value.text) tab.pushUndo(tab.value)+        tab.value = new+    }++    /** Moves the selection without recording an undo step (used by find navigation). */+    fun setSelection(range: TextRange) {+        val tab = currentTab ?: return+        tab.value = tab.value.copy(selection = range)+    }++    fun undo() = currentTab?.undo()++    fun redo() = currentTab?.redo()++    fun save() {+        val tab = currentTab ?: return+        val textToSave = tab.value.text+        viewModelScope.launch {+            val ok = withContext(Dispatchers.IO) {+                runCatching { SafFiles.writeText(context, tab.uri, textToSave) }.isSuccess+            }+            if (ok) tab.savedText = textToSave+        }+    }++    /** Inserts [insert] at the caret, replacing any current selection (used by the Tab button). */+    fun insertText(insert: String) {+        val tab = currentTab ?: return+        val v = tab.value+        val start = v.selection.min+        val end = v.selection.max+        val newText = v.text.substring(0, start) + insert + v.text.substring(end)+        onEditorChange(TextFieldValue(newText, TextRange(start + insert.length)))+    }++    fun toggleSoftWrap() {+        softWrap = !softWrap+        viewModelScope.launch { prefs.setSoftWrap(softWrap) }+    }++    // ---- Find & replace ----++    fun replaceRange(range: IntRange, replacement: String) {+        val tab = currentTab ?: return+        val text = tab.value.text+        if (range.first < 0 || range.last + 1 > text.length) return+        val newText = text.substring(0, range.first) + replacement + text.substring(range.last + 1)+        onEditorChange(TextFieldValue(newText, TextRange(range.first + replacement.length)))+    }++    fun replaceAll(matches: List<IntRange>, replacement: String) {+        val tab = currentTab ?: return+        if (matches.isEmpty()) return+        val text = tab.value.text+        val sb = StringBuilder(text.length)+        var last = 0+        for (m in matches.sortedBy { it.first }) {+            if (m.first < last) continue+            sb.append(text, last, m.first)+            sb.append(replacement)+            last = m.last + 1+        }+        sb.append(text, last, text.length)+        onEditorChange(TextFieldValue(sb.toString(), TextRange(sb.length)))+    }+}
code/src/main/java/com/vayunmathur/code/util/SafFiles.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/SafFiles.kt b/code/src/main/java/com/vayunmathur/code/util/SafFiles.ktnew file mode 100644index 0000000000..322d30cba2--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/SafFiles.kt@@ -0,0 +1,98 @@+package com.vayunmathur.code.util++import android.content.Context+import android.database.Cursor+import android.net.Uri+import android.provider.DocumentsContract+import java.io.BufferedReader++/**+ * A single entry (file or directory) discovered through the Storage Access Framework.+ *+ * We keep the [documentId] around because child enumeration and document-URI+ * construction are both keyed off document ids rather than the URIs themselves.+ */+data class DocEntry(+    val documentId: String,+    val name: String,+    val uri: Uri,+    val isDirectory: Boolean,+)++/**+ * Thin wrappers over [DocumentsContract] + [android.content.ContentResolver].+ *+ * All calls here touch the content resolver and may block, so callers run them off+ * the main thread. Nothing is cached: the file tree is rebuilt lazily as folders+ * expand, which keeps large trees cheap and always in sync with the on-disk state.+ */+object SafFiles {++    /** Resolves the root document of a persisted tree URI into a browsable [DocEntry]. */+    fun rootEntry(context: Context, treeUri: Uri): DocEntry {+        val rootId = DocumentsContract.getTreeDocumentId(treeUri)+        val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, rootId)+        val name = queryDisplayName(context, docUri) ?: treeUri.lastPathSegment.orEmpty()+        return DocEntry(rootId, name, docUri, isDirectory = true)+    }++    /**+     * Lists the direct children of [parentDocumentId] inside [treeUri], sorted with+     * directories first and then case-insensitively by name (VS Code's ordering).+     */+    fun listChildren(context: Context, treeUri: Uri, parentDocumentId: String): List<DocEntry> {+        val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocumentId)+        val result = ArrayList<DocEntry>()+        val projection = arrayOf(+            DocumentsContract.Document.COLUMN_DOCUMENT_ID,+            DocumentsContract.Document.COLUMN_DISPLAY_NAME,+            DocumentsContract.Document.COLUMN_MIME_TYPE,+        )+        context.contentResolver.query(childrenUri, projection, null, null, null)?.use { cursor: Cursor ->+            val idCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)+            val nameCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)+            val mimeCol = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)+            while (cursor.moveToNext()) {+                val docId = cursor.getString(idCol)+                val name = cursor.getString(nameCol) ?: continue+                val mime = cursor.getString(mimeCol)+                val isDir = mime == DocumentsContract.Document.MIME_TYPE_DIR+                val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId)+                result.add(DocEntry(docId, name, docUri, isDir))+            }+        }+        return result.sortedWith(+            compareByDescending<DocEntry> { it.isDirectory }.thenBy { it.name.lowercase() }+        )+    }++    /** Reads a document's display name; used for single-file and external-intent opens. */+    fun queryDisplayName(context: Context, uri: Uri): String? {+        val projection = arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME)+        return runCatching {+            context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->+                if (cursor.moveToFirst()) cursor.getString(0) else null+            }+        }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')+    }++    /** Reads the full UTF-8 text of a document. */+    fun readText(context: Context, uri: Uri): String {+        context.contentResolver.openInputStream(uri).use { input ->+            requireNotNull(input) { "Unable to open $uri for reading" }+            return input.bufferedReader().use(BufferedReader::readText)+        }+    }++    /**+     * Overwrites a document with [text]. The `"wt"` mode truncates first so shrinking+     * a file doesn't leave stale trailing bytes behind.+     */+    fun writeText(context: Context, uri: Uri, text: String) {+        context.contentResolver.openOutputStream(uri, "wt").use { output ->+            requireNotNull(output) { "Unable to open $uri for writing" }+            output.write(text.toByteArray(Charsets.UTF_8))+            output.flush()+        }+    }+}
code/src/main/res/values/strings.xml
diff --git a/code/src/main/res/values/strings.xml b/code/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..04fae3f346--- /dev/null+++ b/code/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Code</string>+</resources>