Modern Apps git

← Modern-Apps.git

code: detect external changes, preserve encoding/line endings, add exit guard

Commit
3f684e00c14d54fab3b2d982494a5415b0fb0b7c
Author
vayun-mathur <[email protected]>
When
2026-08-06 23:41 UTC (4 months ago)
Parents
7e1e9b9

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 9601437cfe..940a2d9e11 100644--- a/code/src/main/java/com/vayunmathur/code/MainActivity.kt+++ b/code/src/main/java/com/vayunmathur/code/MainActivity.kt@@ -65,6 +65,7 @@ class MainActivity : ComponentActivity() {     override fun onResume() {         super.onResume()         hasStoragePermission = Environment.isExternalStorageManager()+        viewModel.checkExternalChanges()     }      override fun onNewIntent(intent: Intent) {
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 0e67d95fdb..89f01a7459 100644--- a/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt+++ b/code/src/main/java/com/vayunmathur/code/ui/EditorScreen.kt@@ -2,6 +2,7 @@ package com.vayunmathur.code.ui  import androidx.compose.ui.res.stringResource import com.vayunmathur.code.R+import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background@@ -36,6 +37,8 @@ import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.code.util.CodeActions@@ -90,6 +93,7 @@ fun EditorPage(     val fileLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.OpenDocument()     ) { uri -> uri?.let(viewModel::openExternal) }+    val activity = LocalContext.current as? android.app.Activity      EditorScreen(         state = viewModel.uiState,@@ -101,6 +105,7 @@ fun EditorPage(         onOpenGit = onOpenGit,         onOpenTerminal = onOpenTerminal,         onOpenPreview = onOpenPreview,+        onExitApp = { activity?.finish() },     ) } @@ -123,6 +128,7 @@ fun EditorScreen(     onOpenGit: () -> Unit = {},     onOpenTerminal: () -> Unit = {},     onOpenPreview: () -> Unit = {},+    onExitApp: () -> 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@@ -139,6 +145,11 @@ fun EditorScreen(     var showGoToLine by remember { mutableStateOf(false) }     var showQuickOpen by remember { mutableStateOf(false) }     var showPalette by remember { mutableStateOf(false) }+    var showExitGuard by remember { mutableStateOf(false) }+    val anyDirty = state.tabs.any { it.isDirty }++    // Guard back/close when there are unsaved changes; offer Save all / Discard / Cancel.+    BackHandler(enabled = anyDirty) { showExitGuard = true }      Box(         Modifier@@ -215,6 +226,13 @@ fun EditorScreen(                         onOpenPalette = { showPalette = true },                     )                     HorizontalDivider()+                    if (tab.changedOnDisk) {+                        DiskChangedBanner(+                            onReload = { actions.reloadFromDisk() },+                            onKeep = { actions.dismissDiskChange() },+                        )+                        HorizontalDivider()+                    }                     CodeEditor(                         tab = tab,                         actions = actions,@@ -271,6 +289,28 @@ fun EditorScreen(             onDismiss = { showGoToLine = false },         )     }+    if (showExitGuard) {+        AlertDialog(+            onDismissRequest = { showExitGuard = false },+            title = { Text(stringResource(R.string.exit_unsaved_title)) },+            text = { Text(stringResource(R.string.exit_unsaved_message)) },+            confirmButton = {+                Row {+                    TextButton(onClick = { showExitGuard = false; onExitApp() }) {+                        Text(stringResource(R.string.discard))+                    }+                    TextButton(onClick = { actions.saveAll(); showExitGuard = false; onExitApp() }) {+                        Text(stringResource(R.string.save_all))+                    }+                }+            },+            dismissButton = {+                TextButton(onClick = { showExitGuard = false }) {+                    Text(stringResource(R.string.cancel))+                }+            },+        )+    }     } } @@ -404,11 +444,38 @@ private fun EditorToolbar(             text = tab.language.label,             color = MaterialTheme.colorScheme.onSurfaceVariant,             style = MaterialTheme.typography.labelMedium,+            modifier = Modifier.padding(start = 12.dp),+        )+        Text(+            text = "${tab.charsetName} \u00B7 ${tab.lineEndingName}",+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            style = MaterialTheme.typography.labelMedium,             modifier = Modifier.padding(horizontal = 12.dp),         )     } } +/** A banner shown when the open file changed on disk under unsaved edits: reload or keep. */+@Composable+private fun DiskChangedBanner(onReload: () -> Unit, onKeep: () -> Unit) {+    Row(+        modifier = Modifier+            .fillMaxWidth()+            .background(MaterialTheme.colorScheme.secondaryContainer)+            .padding(horizontal = 12.dp, vertical = 4.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Text(+            text = stringResource(R.string.disk_changed),+            color = MaterialTheme.colorScheme.onSecondaryContainer,+            style = MaterialTheme.typography.labelMedium,+            modifier = Modifier.weight(1f),+        )+        TextButton(onClick = onReload) { Text(stringResource(R.string.reload)) }+        TextButton(onClick = onKeep) { Text(stringResource(R.string.keep_mine)) }+    }+}+ /** A small dialog that reads a line number and jumps the caret to it. */ @Composable private fun GoToLineDialog(onGo: (Int) -> Unit, onDismiss: () -> Unit) {@@ -454,6 +521,7 @@ private fun editorCommands( ): List<PickerItem> = listOf(     PickerItem(stringResource(R.string.quick_open)) { onQuickOpen() },     PickerItem(stringResource(R.string.save)) { actions.save() },+    PickerItem(stringResource(R.string.save_all)) { actions.saveAll() },     PickerItem(stringResource(R.string.find)) { onToggleFind() },     PickerItem(stringResource(R.string.go_to_line)) { onGoToLine() },     PickerItem(stringResource(R.string.toggle_comment)) { actions.toggleComment() },
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 95ccbf661f..3860478f53 100644--- a/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt+++ b/code/src/main/java/com/vayunmathur/code/util/CodeUiContract.kt@@ -25,6 +25,12 @@ data class TabUiState(     val isDirty: Boolean = false,     val canUndo: Boolean = false,     val canRedo: Boolean = false,+    /** True when the file changed on disk while this (dirty) tab held unsaved edits. */+    val changedOnDisk: Boolean = false,+    /** Charset name shown in the status area (e.g. "UTF-8"). */+    val charsetName: String = "UTF-8",+    /** Line-ending name shown in the status area ("LF" or "CRLF"). */+    val lineEndingName: String = "LF", )  /** One row of the flat, lazily-expanded file tree. */@@ -95,6 +101,16 @@ interface CodeActions {     fun undo() {}     fun redo() {}     fun save() {}++    /** Save every dirty, file-backed tab (used by the exit guard and the palette). */+    fun saveAll() {}++    /** Reload the current tab from disk, discarding in-memory edits ("changed on disk" banner). */+    fun reloadFromDisk() {}++    /** Dismiss the "changed on disk" banner, keeping the in-memory edits. */+    fun dismissDiskChange() {}+     fun toggleSoftWrap() {}     fun insertText(insert: String) {}     fun onEditorChange(new: TextFieldValue) {}
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 e8c4a2affa..ea05f765d6 100644--- a/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt+++ b/code/src/main/java/com/vayunmathur/code/util/EditorViewModel.kt@@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File+import java.nio.charset.Charset import kotlin.coroutines.coroutineContext  /** One expandable row in the file-tree pane; the tree is stored as a flat, ordered list. */@@ -56,6 +57,18 @@ class OpenTab(     var canRedo by mutableStateOf(false)         private set +    // Fidelity metadata so a save round-trips the file byte-for-byte (see [TextEncoding]).+    var charset: Charset = Charsets.UTF_8+    var lineEnding: LineEnding = LineEnding.LF+    var hadBom: Boolean = false++    // Snapshot of the file on disk when it was last opened/saved, for external-change detection.+    var diskModified: Long = 0L+    var diskLength: Long = 0L++    /** Set when the file changed on disk while this tab held unsaved edits (drives the banner). */+    var changedOnDisk by mutableStateOf(false)+     private val undoStack = ArrayDeque<TextFieldValue>()     private val redoStack = ArrayDeque<TextFieldValue>() @@ -203,6 +216,9 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),                     isDirty = it.isDirty,                     canUndo = it.canUndo,                     canRedo = it.canRedo,+                    changedOnDisk = it.changedOnDisk,+                    charsetName = it.charset.name(),+                    lineEndingName = it.lineEnding.name,                 )             },             currentIndex = currentIndex,@@ -265,10 +281,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             val file = File(path)             if (!file.isFile) continue             if (tabs.any { it.key == path }) continue-            val text = withContext(Dispatchers.IO) {-                runCatching { FileFiles.readText(file) }.getOrDefault("")-            }-            tabs.add(OpenTab(file = file, initialName = file.name, initialText = text, language = Language.fromFileName(file.name)))+            tabs.add(makeFileTab(file))         }         currentIndex = tabs.indexOfFirst { it.file?.absolutePath == current }             .takeIf { it >= 0 } ?: if (tabs.isEmpty()) -1 else 0@@ -483,10 +496,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             return         }         viewModelScope.launch {-            val text = withContext(Dispatchers.IO) {-                runCatching { FileFiles.readText(file) }.getOrDefault("")-            }-            tabs.add(OpenTab(file = file, initialName = file.name, initialText = text, language = Language.fromFileName(file.name)))+            tabs.add(makeFileTab(file))             currentIndex = tabs.lastIndex             saveSession()         }@@ -525,6 +535,34 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         }     } +    /** Reads + decodes [file] off the main thread into a fully-populated tab (empty on failure). */+    private suspend fun makeFileTab(file: File, name: String = file.name): OpenTab {+        val loaded = loadFile(file)+        return OpenTab(+            file = file,+            initialName = name,+            initialText = loaded.decoded.text,+            language = Language.fromFileName(name),+        ).apply {+            charset = loaded.decoded.charset+            lineEnding = loaded.decoded.lineEnding+            hadBom = loaded.decoded.hadBom+            diskModified = loaded.modified+            diskLength = loaded.length+        }+    }++    /** Reads [file]'s bytes and decodes them, capturing the on-disk snapshot; safe on failure. */+    private suspend fun loadFile(file: File): LoadedFile = withContext(Dispatchers.IO) {+        runCatching {+            LoadedFile(TextEncoding.decode(FileFiles.readBytes(file)), file.lastModified(), file.length())+        }.getOrDefault(+            LoadedFile(DecodedText("", Charsets.UTF_8, false, LineEnding.LF), file.lastModified(), file.length()),+        )+    }++    private class LoadedFile(val decoded: DecodedText, val modified: Long, val length: Long)+     override fun selectTab(index: Int) {         if (index in tabs.indices) {             currentIndex = index@@ -644,6 +682,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),             gitIsRepo = withContext(Dispatchers.IO) { GitRepo.isRepo(dir) }             if (gitIsRepo) runCatching { loadGitState(dir) }             gitBusy = false+            checkExternalChanges()         }     } @@ -827,17 +866,81 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),      override fun save() {         val tab = currentTab ?: return+        saveTab(tab)+    }++    override fun saveAll() {+        for (tab in tabs) if (tab.file != null && tab.isDirty) saveTab(tab)+    }++    /** Encodes [tab] with its stored charset/BOM/line-ending and writes it, refreshing the snapshot. */+    private fun saveTab(tab: OpenTab) {         val file = tab.file ?: return // external read-only tabs have no save target         val textToSave = tab.value.text+        val bytes = TextEncoding.encode(textToSave, tab.charset, tab.lineEnding, tab.hadBom)         viewModelScope.launch {             val ok = withContext(Dispatchers.IO) {-                runCatching { FileFiles.writeText(file, textToSave) }.isSuccess+                runCatching { FileFiles.writeBytes(file, bytes) }.isSuccess+            }+            if (ok) {+                tab.savedText = textToSave+                tab.changedOnDisk = false+                val (modified, length) = withContext(Dispatchers.IO) { file.lastModified() to file.length() }+                tab.diskModified = modified+                tab.diskLength = length+                if (gitIsRepo) refreshGit()             }-            if (ok) tab.savedText = textToSave-            if (ok && gitIsRepo) refreshGit()         }     } +    /**+     * Compares each open file-backed tab against its on-disk snapshot (called on ON_RESUME and after+     * git actions). A clean tab is silently reloaded; a dirty tab raises its "changed on disk" banner.+     */+    fun checkExternalChanges() {+        if (tabs.isEmpty()) return+        viewModelScope.launch {+            for (tab in tabs) {+                val file = tab.file ?: continue+                val snapshot = withContext(Dispatchers.IO) {+                    if (file.exists()) file.lastModified() to file.length() else null+                } ?: continue+                if (snapshot.first == tab.diskModified && snapshot.second == tab.diskLength) continue+                if (tab.isDirty) tab.changedOnDisk = true else applyReload(tab)+            }+        }+    }++    override fun reloadFromDisk() {+        val tab = currentTab ?: return+        viewModelScope.launch { applyReload(tab) }+    }++    override fun dismissDiskChange() {+        val tab = currentTab ?: return+        viewModelScope.launch {+            val file = tab.file ?: return@launch+            val (modified, length) = withContext(Dispatchers.IO) { file.lastModified() to file.length() }+            tab.diskModified = modified+            tab.diskLength = length+            tab.changedOnDisk = false+        }+    }++    /** Replaces [tab]'s buffer with the current disk contents and refreshes its snapshot. */+    private suspend fun applyReload(tab: OpenTab) {+        val file = tab.file ?: return+        val loaded = loadFile(file)+        tab.value = TextFieldValue(loaded.decoded.text)+        tab.savedText = loaded.decoded.text+        tab.charset = loaded.decoded.charset+        tab.lineEnding = loaded.decoded.lineEnding+        tab.hadBom = loaded.decoded.hadBom+        tab.diskModified = loaded.modified+        tab.diskLength = loaded.length+        tab.changedOnDisk = false+    }+     /** Inserts [insert] at the caret, replacing any current selection (used by the Tab button). */     override fun insertText(insert: String) {         val tab = currentTab ?: return@@ -992,10 +1095,7 @@ class EditorViewModel(application: Application) : AndroidViewModel(application),         }         val file = File(result.path)         viewModelScope.launch {-            val text = withContext(Dispatchers.IO) {-                runCatching { FileFiles.readText(file) }.getOrDefault("")-            }-            tabs.add(OpenTab(file = file, initialName = result.name, initialText = text, language = Language.fromFileName(result.name)))+            tabs.add(makeFileTab(file, result.name))             currentIndex = tabs.lastIndex             goToLine(result.line)             saveSession()
code/src/main/java/com/vayunmathur/code/util/FileFiles.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/FileFiles.kt b/code/src/main/java/com/vayunmathur/code/util/FileFiles.ktindex 6a5b650210..ee3f6ca0bd 100644--- a/code/src/main/java/com/vayunmathur/code/util/FileFiles.kt+++ b/code/src/main/java/com/vayunmathur/code/util/FileFiles.kt@@ -47,6 +47,12 @@ object FileFiles {     /** Overwrites a file with [text] (truncating any previous contents). */     fun writeText(file: File, text: String) = file.writeText(text, Charsets.UTF_8) +    /** Reads a file's raw bytes, so encoding/BOM/line endings can be sniffed and preserved. */+    fun readBytes(file: File): ByteArray = file.readBytes()++    /** Overwrites a file with raw [bytes] (truncating any previous contents). */+    fun writeBytes(file: File, bytes: ByteArray) = file.writeBytes(bytes)+     /**      * Creates a new empty file (and any missing parent directories) under [parent]. Returns the      * new [File], or null if it already exists or creation failed.
code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt
diff --git a/code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt b/code/src/main/java/com/vayunmathur/code/util/TextEncoding.ktnew file mode 100644index 0000000000..8c3e9c7c6b--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/util/TextEncoding.kt@@ -0,0 +1,93 @@+package com.vayunmathur.code.util++import java.nio.charset.Charset++/** The line ending a file uses on disk; the buffer is always normalized to [LF] while editing. */+enum class LineEnding(val sequence: String) {+    LF("\n"),+    CRLF("\r\n"),+}++/**+ * A file's text decoded for editing, plus the fidelity metadata needed to write it back byte-for-byte:+ * the [charset], whether it began with a byte-order mark ([hadBom]) and its dominant [lineEnding].+ * [text] is always normalized to `\n` line endings so the editor only ever deals with LF.+ */+data class DecodedText(+    val text: String,+    val charset: Charset,+    val hadBom: Boolean,+    val lineEnding: LineEnding,+)++/**+ * Pure encoding/line-ending detection so opening a file and saving it round-trips exactly.+ *+ * On open [decode] sniffs a BOM (UTF-8/UTF-16LE/UTF-16BE, else UTF-8), strips it, decodes, records+ * the dominant line ending and normalizes the buffer to `\n`. On save [encode] re-applies the+ * original line ending and BOM in the original charset. No Android dependencies, so it is unit-tested+ * directly on byte arrays.+ */+object TextEncoding {++    private val UTF8_BOM = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte())+    private val UTF16LE_BOM = byteArrayOf(0xFF.toByte(), 0xFE.toByte())+    private val UTF16BE_BOM = byteArrayOf(0xFE.toByte(), 0xFF.toByte())++    /** Decodes [bytes] into editable text plus the metadata needed to re-encode it faithfully. */+    fun decode(bytes: ByteArray): DecodedText {+        val (charset, bomLen, hadBom) = when {+            bytes.startsWith(UTF8_BOM) -> Triple(Charsets.UTF_8, UTF8_BOM.size, true)+            bytes.startsWith(UTF16LE_BOM) -> Triple(Charsets.UTF_16LE, UTF16LE_BOM.size, true)+            bytes.startsWith(UTF16BE_BOM) -> Triple(Charsets.UTF_16BE, UTF16BE_BOM.size, true)+            else -> Triple(Charsets.UTF_8, 0, false)+        }+        val raw = String(bytes, bomLen, bytes.size - bomLen, charset)+        val lineEnding = detectLineEnding(raw)+        return DecodedText(normalizeToLf(raw), charset, hadBom, lineEnding)+    }++    /** Re-applies [lineEnding] and, when [hadBom], the byte-order mark, encoding with [charset]. */+    fun encode(text: String, charset: Charset, lineEnding: LineEnding, hadBom: Boolean): ByteArray {+        val normalized = normalizeToLf(text)+        val withEnding =+            if (lineEnding == LineEnding.CRLF) normalized.replace("\n", "\r\n") else normalized+        val body = withEnding.toByteArray(charset)+        val bom = if (hadBom) bomFor(charset) else ByteArray(0)+        return bom + body+    }++    /** The dominant line ending in [text]: CRLF only when CRLFs are present and not outnumbered. */+    fun detectLineEnding(text: String): LineEnding {+        var crlf = 0+        var lf = 0+        var i = 0+        while (i < text.length) {+            val c = text[i]+            if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') {+                crlf+++                i += 2+            } else {+                if (c == '\n') lf+++                i+++            }+        }+        return if (crlf > 0 && crlf >= lf) LineEnding.CRLF else LineEnding.LF+    }++    /** Collapses CRLF and lone CR to LF so the editor buffer is always `\n`-terminated. */+    fun normalizeToLf(text: String): String = text.replace("\r\n", "\n").replace('\r', '\n')++    private fun bomFor(charset: Charset): ByteArray = when (charset) {+        Charsets.UTF_8 -> UTF8_BOM+        Charsets.UTF_16LE -> UTF16LE_BOM+        Charsets.UTF_16BE -> UTF16BE_BOM+        else -> ByteArray(0)+    }++    private fun ByteArray.startsWith(prefix: ByteArray): Boolean {+        if (size < prefix.size) return false+        for (i in prefix.indices) if (this[i] != prefix[i]) return false+        return true+    }+}
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 14dfa63843..8dab8230f9 100644--- a/code/src/main/res/values/strings.xml+++ b/code/src/main/res/values/strings.xml@@ -95,4 +95,10 @@     <string name="save">Save</string>     <string name="undo">Undo</string>     <string name="redo">Redo</string>+    <string name="save_all">Save all</string>+    <string name="disk_changed">This file changed on disk.</string>+    <string name="reload">Reload</string>+    <string name="keep_mine">Keep mine</string>+    <string name="exit_unsaved_title">Unsaved changes</string>+    <string name="exit_unsaved_message">You have unsaved changes. Save them before leaving?</string> </resources>
code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt b/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.ktnew file mode 100644index 0000000000..134f50970b--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/util/TextEncodingTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.code.util++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Unit tests for the pure encoding / line-ending detection and round-tripping. */+class TextEncodingTest {++    @Test+    fun detectsLfWhenNoCarriageReturns() {+        assertEquals(LineEnding.LF, TextEncoding.detectLineEnding("a\nb\nc"))+    }++    @Test+    fun detectsCrlfWhenPresent() {+        assertEquals(LineEnding.CRLF, TextEncoding.detectLineEnding("a\r\nb\r\nc"))+    }++    @Test+    fun mixedEndingsPickTheMajority() {+        // Two CRLF vs one lone LF -> CRLF.+        assertEquals(LineEnding.CRLF, TextEncoding.detectLineEnding("a\r\nb\r\nc\nd"))+        // One CRLF vs two lone LF -> LF.+        assertEquals(LineEnding.LF, TextEncoding.detectLineEnding("a\r\nb\nc\nd"))+    }++    @Test+    fun normalizeCollapsesCrlfAndLoneCr() {+        assertEquals("a\nb\nc", TextEncoding.normalizeToLf("a\r\nb\rc"))+    }++    @Test+    fun decodesPlainUtf8() {+        val decoded = TextEncoding.decode("hello".toByteArray(Charsets.UTF_8))+        assertEquals("hello", decoded.text)+        assertEquals(Charsets.UTF_8, decoded.charset)+        assertFalse(decoded.hadBom)+        assertEquals(LineEnding.LF, decoded.lineEnding)+    }++    @Test+    fun decodesUtf8WithBomAndStripsIt() {+        val bytes = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + "hi".toByteArray()+        val decoded = TextEncoding.decode(bytes)+        assertEquals("hi", decoded.text)+        assertTrue(decoded.hadBom)+    }++    @Test+    fun decodesUtf16LeBom() {+        val bytes = byteArrayOf(0xFF.toByte(), 0xFE.toByte()) + "hi".toByteArray(Charsets.UTF_16LE)+        val decoded = TextEncoding.decode(bytes)+        assertEquals("hi", decoded.text)+        assertEquals(Charsets.UTF_16LE, decoded.charset)+        assertTrue(decoded.hadBom)+    }++    @Test+    fun crlfRoundTripsExactly() {+        val original = "line1\r\nline2\r\n".toByteArray(Charsets.UTF_8)+        val decoded = TextEncoding.decode(original)+        assertEquals("line1\nline2\n", decoded.text)+        val reencoded = TextEncoding.encode(decoded.text, decoded.charset, decoded.lineEnding, decoded.hadBom)+        assertContentEquals(original, reencoded)+    }++    @Test+    fun utf8BomRoundTripsExactly() {+        val original = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) ++            "x\r\ny".toByteArray(Charsets.UTF_8)+        val decoded = TextEncoding.decode(original)+        val reencoded = TextEncoding.encode(decoded.text, decoded.charset, decoded.lineEnding, decoded.hadBom)+        assertContentEquals(original, reencoded)+    }++    @Test+    fun lfFileWithoutBomRoundTrips() {+        val original = "a\nb\n".toByteArray(Charsets.UTF_8)+        val decoded = TextEncoding.decode(original)+        val reencoded = TextEncoding.encode(decoded.text, decoded.charset, decoded.lineEnding, decoded.hadBom)+        assertContentEquals(original, reencoded)+    }+}