code: add virtualized editor engine behind experimental flag
- Commit
06b798e22a4a3faa7c25d2128ba4cac36cff31be- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-07 00:07 UTC (4 months ago)
- Parents
3c9e40f
Diff
code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.ktnew file mode 100644index 0000000000..87e7263783--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/ui/CodeEditorView.kt@@ -0,0 +1,279 @@+package com.vayunmathur.code.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.Orientation+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.rememberScrollableState+import androidx.compose.foundation.gestures.scrollable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.isCtrlPressed+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.input.key.type+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.drawText+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.code.syntax.LanguageSpec+import com.vayunmathur.code.syntax.SyntaxColors+import com.vayunmathur.code.syntax.rememberSyntaxColors+import com.vayunmathur.code.util.CodeActions+import com.vayunmathur.code.util.TabUiState+import com.vayunmathur.library.ui.MaterialTheme++/**+ * The experimental virtualized editor engine (Phase 7). A [Canvas] draws only the lines inside the+ * viewport, so syntax highlighting is computed per-visible-line instead of over the whole document.+ * It reuses the existing edit pipeline: input is routed through [CodeActions.onEditorChange] /+ * [CodeActions.setSelection], so undo/redo, auto-save and smart input all keep working.+ *+ * v1 scope (documented follow-ups): hardware-keyboard input and tap-to-place-caret are supported;+ * soft-keyboard IME and soft-wrap are not yet wired. Gated behind the `experimentalEditor` pref, so+ * the stable [CodeEditor] stays the default until this reaches parity.+ */+@Composable+fun CodeEditorView(+ tab: TabUiState,+ actions: CodeActions,+ fontSize: Int,+ editorTheme: String,+ modifier: Modifier = Modifier,+ onValueChangeOverride: ((TextFieldValue) -> Unit)? = null,+) {+ val value = tab.value+ val text = value.text+ val colors = rememberSyntaxColors(editorTheme)+ val onSurface = MaterialTheme.colorScheme.onSurface+ val gutterColor = MaterialTheme.colorScheme.onSurfaceVariant+ val caretColor = MaterialTheme.colorScheme.primary+ val spec = tab.language.spec++ val measurer = rememberTextMeasurer()+ val density = LocalDensity.current+ val style = remember(fontSize, onSurface) {+ TextStyle(fontFamily = FontFamily.Monospace, fontSize = fontSize.sp, color = onSurface)+ }+ val metrics = remember(style) { measurer.measure("M", style) }+ val lineHeight = metrics.size.height.toFloat().coerceAtLeast(1f)+ val charWidth = metrics.size.width.toFloat().coerceAtLeast(1f)++ val lines = remember(text) { text.split("\n") }+ val lineStarts = remember(text) {+ IntArray(lines.size).also { starts ->+ var acc = 0+ for (i in lines.indices) {+ starts[i] = acc+ acc += lines[i].length + 1+ }+ }+ }+ val longestLine = remember(text) { lines.maxOfOrNull { it.length } ?: 0 }+ val gutterWidth = with(density) { ((lines.size.toString().length * 10) + 16).dp.toPx() }++ var scrollY by remember { mutableStateOf(0f) }+ var scrollX by remember { mutableStateOf(0f) }+ var viewport by remember { mutableStateOf(IntSize.Zero) }+ val focusRequester = remember { FocusRequester() }++ val totalHeight = lineHeight * lines.size+ val totalWidth = gutterWidth + longestLine * charWidth + charWidth+ val maxScrollY = (totalHeight - viewport.height).coerceAtLeast(0f)+ val maxScrollX = (totalWidth - viewport.width).coerceAtLeast(0f)+ scrollY = scrollY.coerceIn(0f, maxScrollY)+ scrollX = scrollX.coerceIn(0f, maxScrollX)++ val vScroll = rememberScrollableState { delta ->+ val newY = (scrollY - delta).coerceIn(0f, maxScrollY)+ val consumed = scrollY - newY+ scrollY = newY+ consumed+ }+ val hScroll = rememberScrollableState { delta ->+ val newX = (scrollX - delta).coerceIn(0f, maxScrollX)+ val consumed = scrollX - newX+ scrollX = newX+ consumed+ }++ fun offsetAt(x: Float, y: Float): Int {+ val line = ((y + scrollY) / lineHeight).toInt().coerceIn(0, lines.size - 1)+ val col = (((x + scrollX) - gutterWidth) / charWidth).toInt().coerceIn(0, lines[line].length)+ return (lineStarts[line] + col).coerceIn(0, text.length)+ }++ val emit: (TextFieldValue) -> Unit = onValueChangeOverride ?: actions::onEditorChange++ Canvas(+ modifier+ .fillMaxSize()+ .onSizeChanged { viewport = it }+ .scrollable(vScroll, Orientation.Vertical)+ .scrollable(hScroll, Orientation.Horizontal)+ .pointerInput(text) {+ detectTapGestures { pos ->+ val offset = offsetAt(pos.x, pos.y)+ actions.setSelection(TextRange(offset))+ focusRequester.requestFocus()+ }+ }+ .focusRequester(focusRequester)+ .focusable()+ .onPreviewKeyEvent { event ->+ if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false+ handleKey(event, value, emit) { range -> actions.setSelection(range) }+ },+ ) {+ viewport = IntSize(size.width.toInt(), size.height.toInt())+ val caret = if (value.selection.collapsed) value.selection.start else -1+ val selMin = value.selection.min+ val selMax = value.selection.max++ val first = (scrollY / lineHeight).toInt().coerceIn(0, (lines.size - 1).coerceAtLeast(0))+ val visible = (size.height / lineHeight).toInt() + 2+ val last = (first + visible).coerceAtMost(lines.size - 1)++ for (i in first..last) {+ val y = i * lineHeight - scrollY+ val lineStart = lineStarts[i]+ val lineLen = lines[i].length++ // Current-line background.+ if (caret in lineStart..(lineStart + lineLen)) {+ drawRect(colors.currentLine, topLeft = Offset(0f, y), size = Size(size.width, lineHeight))+ }++ // Selection background on this line.+ if (selMax > selMin) {+ val a = (selMin - lineStart).coerceIn(0, lineLen)+ val b = (selMax - lineStart).coerceIn(0, lineLen)+ if (b > a || (selMin <= lineStart + lineLen && selMax > lineStart + lineLen)) {+ val endCol = if (selMax > lineStart + lineLen) lineLen else b+ val startX = gutterWidth + a * charWidth - scrollX+ val width = ((endCol - a).coerceAtLeast(0)) * charWidth + if (selMax > lineStart + lineLen) charWidth else 0f+ if (width > 0f) drawRect(colors.match, topLeft = Offset(startX, y), size = Size(width, lineHeight))+ }+ }++ // Gutter line number.+ val number = measurer.measure(AnnotatedString((i + 1).toString()), style)+ drawText(number, color = gutterColor, topLeft = Offset(gutterWidth - number.size.width - 6f, y))++ // Line text with per-line syntax colors.+ val annotated = annotatedLine(lines[i], spec, colors)+ val layout = measurer.measure(annotated, style)+ drawText(layout, topLeft = Offset(gutterWidth - scrollX, y))++ // Caret.+ if (caret in lineStart..(lineStart + lineLen)) {+ val col = caret - lineStart+ val caretX = gutterWidth + col * charWidth - scrollX+ drawRect(caretColor, topLeft = Offset(caretX, y), size = Size(2f, lineHeight))+ }+ }+ }+}++/** Tokenizes a single line with [spec] and paints rainbow brackets; returns a colored string. */+private fun annotatedLine(line: String, spec: LanguageSpec?, colors: SyntaxColors): AnnotatedString {+ if (spec == null || line.isEmpty() || line.length > MAX_LINE_HIGHLIGHT) return AnnotatedString(line)+ val builder = AnnotatedString.Builder(line)+ if (colors.brackets.isNotEmpty()) {+ var depth = 0+ val n = colors.brackets.size+ for (i in line.indices) {+ when (line[i]) {+ '(', '[', '{' -> {+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ depth+++ }+ ')', ']', '}' -> {+ depth = (depth - 1).coerceAtLeast(0)+ builder.addStyle(SpanStyle(color = colors.brackets[depth % n]), i, i + 1)+ }+ }+ }+ }+ for (match in spec.regex.findAll(line)) {+ val kind = spec.kindFor(match) ?: continue+ builder.addStyle(SpanStyle(color = colors.colorFor(kind)), match.range.first, match.range.last + 1)+ }+ return builder.toAnnotatedString()+}++/**+ * Handles a hardware key press, producing the resulting [TextFieldValue] (via [emit]) or a caret+ * move (via [move]). Text inserts/deletes go through [emit] so the ViewModel's smart input,+ * undo/redo and auto-save all apply. Returns true when the event was consumed.+ */+private fun handleKey(+ event: androidx.compose.ui.input.key.KeyEvent,+ value: TextFieldValue,+ emit: (TextFieldValue) -> Unit,+ move: (TextRange) -> Unit,+): Boolean {+ val text = value.text+ val start = value.selection.min+ val end = value.selection.max+ when (event.key) {+ Key.Backspace -> {+ if (start != end) {+ emit(TextFieldValue(text.substring(0, start) + text.substring(end), TextRange(start)))+ } else if (start > 0) {+ emit(TextFieldValue(text.substring(0, start - 1) + text.substring(start), TextRange(start - 1)))+ }+ return true+ }+ Key.Delete -> {+ if (start != end) {+ emit(TextFieldValue(text.substring(0, start) + text.substring(end), TextRange(start)))+ } else if (start < text.length) {+ emit(TextFieldValue(text.substring(0, start) + text.substring(start + 1), TextRange(start)))+ }+ return true+ }+ Key.DirectionLeft -> {+ move(TextRange((start - 1).coerceAtLeast(0))); return true+ }+ Key.DirectionRight -> {+ move(TextRange((end + 1).coerceAtMost(text.length))); return true+ }+ Key.Enter, Key.NumPadEnter -> {+ emit(TextFieldValue(text.substring(0, start) + "\n" + text.substring(end), TextRange(start + 1)))+ return true+ }+ }+ if (event.isCtrlPressed) return false+ val codePoint = event.nativeKeyEvent.unicodeChar+ if (codePoint != 0) {+ val ch = codePoint.toChar()+ emit(TextFieldValue(text.substring(0, start) + ch + text.substring(end), TextRange(start + 1)))+ return true+ }+ return false+}++private const val MAX_LINE_HIGHLIGHT = 2000
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 034d51772f..12ce03e196 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -262,19 +262,29 @@ fun EditorScreen( modifier = Modifier.weight(1f), ) } else {- CodeEditor(- tab = tab,- actions = actions,- softWrap = state.softWrap,- fontSize = state.fontSize,- showFind = showFind,- onCloseFind = { showFind = false },- modifier = Modifier.weight(1f),- initialQuery = initialFind.orEmpty(),- completions = state.completions,- showCompletions = state.showCompletions,- editorTheme = state.editorTheme,- )+ if (state.experimentalEditor) {+ CodeEditorView(+ tab = tab,+ actions = actions,+ fontSize = state.fontSize,+ editorTheme = state.editorTheme,+ modifier = Modifier.weight(1f),+ )+ } else {+ CodeEditor(+ tab = tab,+ actions = actions,+ softWrap = state.softWrap,+ fontSize = state.fontSize,+ showFind = showFind,+ onCloseFind = { showFind = false },+ modifier = Modifier.weight(1f),+ initialQuery = initialFind.orEmpty(),+ completions = state.completions,+ showCompletions = state.showCompletions,+ editorTheme = state.editorTheme,+ )+ } } } }
code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt
diff --git a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.ktindex 155863f10b..2ad7040d20 100644--- a/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/SettingsPage.kt@@ -118,6 +118,13 @@ fun SettingsPage(viewModel: EditorViewModel, backStack: NavBackStack<Route>) { checked = viewModel.autoSave, onCheckedChange = viewModel::setAutoSave, )+ SettingsDivider()+ SettingsSwitchRow(+ title = stringResource(R.string.experimental_editor),+ supportingText = stringResource(R.string.experimental_editor_desc),+ checked = viewModel.experimentalEditor,+ onCheckedChange = viewModel::setExperimentalEditor,+ ) } SettingsSection(title = stringResource(R.string.user_snippets)) {
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 4454f75668..98db17c99f 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -78,6 +78,8 @@ data class CodeUiState( val completions: List<Completion> = emptyList(), val showCompletions: Boolean = false, val editorTheme: String = EditorThemes.DEFAULT,+ /** When true, the editing surface uses the experimental virtualized [CodeEditorView]. */+ val experimentalEditor: Boolean = false, /** All files under the open project, for quick-open (built lazily, cached in the ViewModel). */ val projectFiles: List<ProjectFileEntry> = emptyList(), /** Most-recently-opened files, newest first, shown in quick-open when the query is empty. */
code/src/main/java/com/vayunmathur/code/util/EditorDocument.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorDocument.kt b/code/src/main/java/com/vayunmathur/code/util/EditorDocument.ktnew file mode 100644index 0000000000..ff2017a4ef--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/EditorDocument.kt@@ -0,0 +1,123 @@+package com.vayunmathur.code.util++/** A single replacement: swap the half-open range `[start, end)` for [text]. */+data class Edit(val start: Int, val end: Int, val text: String)++/**+ * A line-indexed text buffer for the virtualized editor engine. Pure (no Android dependencies) and+ * unit-tested. Provides fast line โ offset mapping (cached, rebuilt on edit), single [replace] edits,+ * multi-caret [applyEdits] applied right-to-left so earlier offsets stay valid, and grouped+ * undo/redo mirroring the per-tab deque semantics of the old editor.+ */+class EditorDocument(initial: String = "") {++ private val builder = StringBuilder(initial)+ private var cachedLineStarts: IntArray? = null++ private val undoStack = ArrayDeque<String>()+ private val redoStack = ArrayDeque<String>()++ val text: String get() = builder.toString()+ val length: Int get() = builder.length++ /** Offsets where each line begins; always starts with 0. Rebuilt lazily after edits. */+ private fun lineStarts(): IntArray {+ cachedLineStarts?.let { return it }+ val starts = ArrayList<Int>()+ starts.add(0)+ for (i in 0 until builder.length) {+ if (builder[i] == '\n') starts.add(i + 1)+ }+ return starts.toIntArray().also { cachedLineStarts = it }+ }++ fun lineCount(): Int = lineStarts().size++ /** 0-based line โ offset of its first character. */+ fun lineStart(line: Int): Int {+ val starts = lineStarts()+ return starts[line.coerceIn(0, starts.size - 1)]+ }++ /** 0-based line โ offset just past its last character, excluding the trailing newline. */+ fun lineEnd(line: Int): Int {+ val starts = lineStarts()+ val clamped = line.coerceIn(0, starts.size - 1)+ return if (clamped + 1 < starts.size) starts[clamped + 1] - 1 else builder.length+ }++ fun lineText(line: Int): String = builder.substring(lineStart(line), lineEnd(line))++ /** The 0-based line containing [offset] (binary search over the line-start table). */+ fun lineOfOffset(offset: Int): Int {+ val target = offset.coerceIn(0, builder.length)+ val starts = lineStarts()+ var lo = 0+ var hi = starts.size - 1+ while (lo < hi) {+ val mid = (lo + hi + 1) ushr 1+ if (starts[mid] <= target) lo = mid else hi = mid - 1+ }+ return lo+ }++ fun columnOfOffset(offset: Int): Int = offset.coerceIn(0, builder.length) - lineStart(lineOfOffset(offset))++ fun offsetOf(line: Int, column: Int): Int {+ val start = lineStart(line)+ val end = lineEnd(line)+ return (start + column).coerceIn(start, end)+ }++ /** Replaces the half-open range `[start, end)` with [newText] as one undo step. */+ fun replace(start: Int, end: Int, newText: String) {+ applyEdits(listOf(Edit(start, end, newText)))+ }++ /**+ * Applies several non-overlapping [edits] as a single grouped undo step. Edits are sorted and+ * applied from the highest offset down so that earlier offsets remain valid as the text mutates.+ */+ fun applyEdits(edits: List<Edit>) {+ if (edits.isEmpty()) return+ pushUndo()+ val ordered = edits.sortedByDescending { it.start }+ for (edit in ordered) {+ val s = edit.start.coerceIn(0, builder.length)+ val e = edit.end.coerceIn(s, builder.length)+ builder.replace(s, e, edit.text)+ }+ cachedLineStarts = null+ }++ private fun pushUndo() {+ undoStack.addLast(builder.toString())+ if (undoStack.size > UNDO_LIMIT) undoStack.removeFirst()+ redoStack.clear()+ }++ val canUndo: Boolean get() = undoStack.isNotEmpty()+ val canRedo: Boolean get() = redoStack.isNotEmpty()++ fun undo() {+ val previous = undoStack.removeLastOrNull() ?: return+ redoStack.addLast(builder.toString())+ setTextInternal(previous)+ }++ fun redo() {+ val next = redoStack.removeLastOrNull() ?: return+ undoStack.addLast(builder.toString())+ setTextInternal(next)+ }++ private fun setTextInternal(value: String) {+ builder.setLength(0)+ builder.append(value)+ cachedLineStarts = null+ }++ private companion object {+ const val UNDO_LIMIT = 100+ }+}
code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.ktindex 1342b750fd..a101216803 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorPrefs.kt@@ -34,6 +34,8 @@ class EditorPrefs(context: Context) { val autoCloseBrackets: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_CLOSE_KEY] ?: true } val autoSave: Flow<Boolean> = appContext.editorDataStore.data.map { it[AUTO_SAVE_KEY] ?: false }+ val experimentalEditor: Flow<Boolean> =+ appContext.editorDataStore.data.map { it[EXPERIMENTAL_EDITOR_KEY] ?: false } val editorTheme: Flow<String> = appContext.editorDataStore.data.map { it[EDITOR_THEME_KEY] ?: EditorThemes.DEFAULT } @@ -96,6 +98,10 @@ class EditorPrefs(context: Context) { appContext.editorDataStore.edit { it[AUTO_SAVE_KEY] = enabled } } + suspend fun setExperimentalEditor(enabled: Boolean) {+ appContext.editorDataStore.edit { it[EXPERIMENTAL_EDITOR_KEY] = enabled }+ }+ suspend fun setEditorTheme(theme: String) { appContext.editorDataStore.edit { it[EDITOR_THEME_KEY] = theme } }@@ -183,6 +189,7 @@ class EditorPrefs(context: Context) { private val AUTO_INDENT_KEY = booleanPreferencesKey("auto_indent") private val AUTO_CLOSE_KEY = booleanPreferencesKey("auto_close_brackets") private val AUTO_SAVE_KEY = booleanPreferencesKey("auto_save")+ private val EXPERIMENTAL_EDITOR_KEY = booleanPreferencesKey("experimental_editor") private val EDITOR_THEME_KEY = stringPreferencesKey("editor_theme") private val SESSION_PATHS_KEY = stringPreferencesKey("session_paths") private val SESSION_CURRENT_KEY = stringPreferencesKey("session_current")
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 1aa5b44a24..1325aea7aa 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -162,6 +162,8 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), val autoSave: Boolean get() = _autoSave.value private val _editorTheme = mutableStateOf(EditorThemes.DEFAULT) val editorTheme: String get() = _editorTheme.value+ private val _experimentalEditor = mutableStateOf(false)+ val experimentalEditor: Boolean get() = _experimentalEditor.value private var autoSaveJob: Job? = null // ---- Project search ----@@ -252,6 +254,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), completions = completions.toList(), showCompletions = showCompletions, editorTheme = editorTheme,+ experimentalEditor = experimentalEditor, projectFiles = projectFiles.toList(), recentFiles = recentPaths.map { toProjectEntry(File(it)) }, )@@ -265,6 +268,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { _autoCloseBrackets.value = prefs.autoCloseBrackets.first() } viewModelScope.launch { _autoSave.value = prefs.autoSave.first() } viewModelScope.launch { _editorTheme.value = prefs.editorTheme.first() }+ viewModelScope.launch { _experimentalEditor.value = prefs.experimentalEditor.first() } viewModelScope.launch { _gitUsername.value = prefs.gitUsername.first() } viewModelScope.launch { _gitToken.value = prefs.gitToken.first() } viewModelScope.launch { _gitAuthorName.value = prefs.gitAuthorName.first() }@@ -1079,6 +1083,11 @@ class EditorViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { prefs.setEditorTheme(theme) } } + fun setExperimentalEditor(enabled: Boolean) {+ _experimentalEditor.value = enabled+ viewModelScope.launch { prefs.setExperimentalEditor(enabled) }+ }+ // ---- Find & replace ---- override fun replaceRange(range: IntRange, replacement: String) {
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 dc81ceb71e..cc907b259c 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -123,4 +123,6 @@ <string name="conflict_keep_theirs">Theirs</string> <string name="conflict_keep_both">Both</string> <string name="split_view">Split view</string>+ <string name="experimental_editor">Experimental editor</string>+ <string name="experimental_editor_desc">Use the new virtualized editor engine (hardware keyboard; work in progress)</string> </resources>
code/src/test/java/com/vayunmathur/code/util/EditorDocumentTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/EditorDocumentTest.kt b/code/src/test/java/com/vayunmathur/code/util/EditorDocumentTest.ktnew file mode 100644index 0000000000..5361ae0ff6--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/EditorDocumentTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.code.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Unit tests for the pure line-indexed document model. */+class EditorDocumentTest {++ @Test+ fun lineCountAndBounds() {+ val doc = EditorDocument("a\nbb\nccc")+ assertEquals(3, doc.lineCount())+ assertEquals(0, doc.lineStart(0))+ assertEquals(1, doc.lineEnd(0))+ assertEquals(2, doc.lineStart(1))+ assertEquals(4, doc.lineEnd(1))+ assertEquals(5, doc.lineStart(2))+ assertEquals(8, doc.lineEnd(2))+ }++ @Test+ fun lineTextExcludesNewline() {+ val doc = EditorDocument("one\ntwo\n")+ assertEquals("one", doc.lineText(0))+ assertEquals("two", doc.lineText(1))+ assertEquals("", doc.lineText(2)) // trailing empty line after final newline+ }++ @Test+ fun lineOfOffsetAndColumn() {+ val doc = EditorDocument("ab\ncd")+ assertEquals(0, doc.lineOfOffset(0))+ assertEquals(0, doc.lineOfOffset(2))+ assertEquals(1, doc.lineOfOffset(3))+ assertEquals(1, doc.lineOfOffset(5))+ assertEquals(1, doc.columnOfOffset(4)) // 'd' is column 1 on line 1+ }++ @Test+ fun offsetOfClampsToLine() {+ val doc = EditorDocument("abc\nde")+ assertEquals(1, doc.offsetOf(0, 1))+ assertEquals(3, doc.offsetOf(0, 99)) // clamped to line end+ assertEquals(4, doc.offsetOf(1, 0))+ }++ @Test+ fun replaceUpdatesTextAndLineIndex() {+ val doc = EditorDocument("hello world")+ doc.replace(6, 11, "there")+ assertEquals("hello there", doc.text)+ doc.replace(5, 5, "\n")+ assertEquals(2, doc.lineCount())+ assertEquals("hello", doc.lineText(0))+ assertEquals(" there", doc.lineText(1))+ }++ @Test+ fun applyEditsRightToLeftKeepsOffsetsValid() {+ val doc = EditorDocument("0123456789")+ // Two non-overlapping edits given in ascending order; must still land correctly.+ doc.applyEdits(listOf(Edit(0, 1, "X"), Edit(9, 10, "Y")))+ assertEquals("X12345678Y", doc.text)+ }++ @Test+ fun applyEditsInsertionsAtMultipleCarets() {+ val doc = EditorDocument("a b c")+ // Insert '*' before each letter (carets at 0,2,4).+ doc.applyEdits(listOf(Edit(0, 0, "*"), Edit(2, 2, "*"), Edit(4, 4, "*")))+ assertEquals("*a *b *c", doc.text)+ }++ @Test+ fun undoRedoRoundTrips() {+ val doc = EditorDocument("start")+ assertFalse(doc.canUndo)+ doc.replace(5, 5, "!")+ assertEquals("start!", doc.text)+ assertTrue(doc.canUndo)+ doc.undo()+ assertEquals("start", doc.text)+ assertTrue(doc.canRedo)+ doc.redo()+ assertEquals("start!", doc.text)+ }++ @Test+ fun groupedEditsAreOneUndoStep() {+ val doc = EditorDocument("a b c")+ doc.applyEdits(listOf(Edit(0, 0, "*"), Edit(2, 2, "*")))+ doc.undo()+ assertEquals("a b c", doc.text)+ }+}