Modern Apps git

← Modern-Apps.git

logviewer: streamed logs, in-place filters, dropdowns, share FAB

Commit
4f303d3b801030613695870ff4df21c31abc3312
Author
vayun-mathur <[email protected]>
When
2026-10-26 20:11 UTC (1 month ago)
Parents
27448b5

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/MultiSelectDropdown.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/MultiSelectDropdown.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/MultiSelectDropdown.ktnew file mode 100644index 0000000000..ff00b110ad--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/MultiSelectDropdown.kt@@ -0,0 +1,50 @@+package com.vayunmathur.library.ui++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++/**+ * [SelectDropdown] for several values at once: each option toggles in place and the menu stays+ * open, and the new selection is applied once, when the menu closes.+ *+ * Applying on close rather than per toggle is the point: picking three options should cost one+ * reload, not three. An empty selection is discarded, since "none of them" is never a valid filter.+ */+@Composable+fun <T> MultiSelectDropdown(+    label: String,+    options: List<T>,+    selected: List<T>,+    itemLabel: @Composable (T) -> String,+    onApply: (List<T>) -> Unit,+    modifier: Modifier = Modifier,+) {+    var expanded by remember { mutableStateOf(false) }+    var staged by remember { mutableStateOf(emptySet<T>()) }+    DropdownTrigger(+        label = label,+        expanded = expanded,+        onExpandedChange = { open ->+            if (open) {+                staged = selected.toSet()+            } else if (staged.isNotEmpty() && staged != selected.toSet()) {+                onApply(options.filter { it in staged })+            }+            expanded = open+        },+        modifier = modifier,+    ) {+        for (option in options) {+            CheckableDropdownMenuItem(+                checked = option in staged,+                onCheckedChange = { checked -> staged = if (checked) staged + option else staged - option },+                text = { Text(itemLabel(option)) },+                checkedLeadingIcon = { IconCheck() },+            )+        }+    }+}
library/ui/src/main/java/com/vayunmathur/library/ui/SelectDropdown.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/SelectDropdown.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/SelectDropdown.ktnew file mode 100644index 0000000000..cc5565fd78--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/SelectDropdown.kt@@ -0,0 +1,61 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.ColumnScope+import androidx.compose.foundation.layout.Row+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.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight++/**+ * A compact top-bar picker: the current value abbreviated as [label] with a drop arrow, opening a+ * menu of [options]. The same shape as the calendar's day/week/month switch.+ */+@Composable+fun <T> SelectDropdown(+    label: String,+    options: List<T>,+    selected: T,+    itemLabel: @Composable (T) -> String,+    onSelect: (T) -> Unit,+    modifier: Modifier = Modifier,+) {+    var expanded by remember { mutableStateOf(false) }+    DropdownTrigger(label, expanded, onExpandedChange = { expanded = it }, modifier) {+        for (option in options) {+            SelectableDropdownMenuItem(+                selected = option == selected,+                onClick = {+                    expanded = false+                    if (option != selected) onSelect(option)+                },+                text = { Text(itemLabel(option)) },+                selectedLeadingIcon = { IconCheck() },+            )+        }+    }+}++@Composable+internal fun DropdownTrigger(+    label: String,+    expanded: Boolean,+    onExpandedChange: (Boolean) -> Unit,+    modifier: Modifier = Modifier,+    menu: @Composable ColumnScope.() -> Unit,+) {+    Box(modifier) {+        TextButton(onClick = { onExpandedChange(true) }) {+            Row(verticalAlignment = Alignment.CenterVertically) {+                Text(label, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)+                IconArrowDropDown(tint = MaterialTheme.colorScheme.primary)+            }+        }+        DropdownMenu(expanded = expanded, onDismissRequest = { onExpandedChange(false) }, content = menu)+    }+}
logviewer/AGENTS.md
diff --git a/logviewer/AGENTS.md b/logviewer/AGENTS.mdindex dffff86328..5ec3b5416a 100644--- a/logviewer/AGENTS.md+++ b/logviewer/AGENTS.md@@ -41,8 +41,6 @@ _Install: ./install logviewer (dev by default)._ - com/vayunmathur/logviewer/ui/LogViewerScreen.kt - com/vayunmathur/logviewer/ui/LogViewerPage.kt - com/vayunmathur/logviewer/ui/components/LogLineList.kt-- com/vayunmathur/logviewer/ui/dialogs/LogBuffersDialog.kt-- com/vayunmathur/logviewer/ui/dialogs/LogLevelDialog.kt - com/vayunmathur/logviewer/ui/dialogs/StackTraceDialog.kt - com/vayunmathur/logviewer/ui/dialogs/TextInputDialog.kt 
logviewer/src/main/java/com/vayunmathur/logviewer/domain/LogDocument.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/domain/LogDocument.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/domain/LogDocument.ktindex 053c367103..37fa4531ea 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/domain/LogDocument.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/domain/LogDocument.kt@@ -10,43 +10,39 @@ import java.util.UUID  * formatting be reused by the screen, the clipboard and the file writer without any of them  * agreeing on it separately.  *- * [description] is the one part the user edits, and it is not held here: it is screen state, and- * every function that needs it takes it as a parameter.+ * Held as lines rather than one string: a full logcat is tens of megabytes, and the list, the+ * clipboard and the file writer all want it line by line. Keeping one copy and viewing it in each+ * shape is what stops a large log from sitting in the heap several times over.  */-data class LogDocument(+class LogDocument(     val kind: LogKind,     /** The app the log is about - the one that crashed, or the one logcat is filtered on. */     val sourcePackage: String?,     val title: String,-    val header: String,-    val body: String,+    headerLines: List<String>,+    val bodyLines: List<String>, ) {-    /**-     * Whether the bottom-left button offers Copy rather than Save.-     *-     * Both the character and the byte length are checked because the limit being approximated is a-     * binder transaction, which is bytes, while the cheap check is characters.-     */-    val canCopy: Boolean =-        body.length < MAX_SIZE_FOR_COPY && body.toByteArray(Charsets.UTF_8).size < MAX_SIZE_FOR_COPY+    constructor(kind: LogKind, sourcePackage: String?, title: String, header: String, body: String) :+        this(kind, sourcePackage, title, splitLines(header), splitLines(body))      /** Empty when there is no header at all, so the screen does not render a blank separator. */-    fun headerLines(): List<String> {-        val lines = splitLines(header)-        return if (lines.size == 1 && lines[0].isBlank()) emptyList() else lines-    }--    fun bodyLines(): List<String> = splitLines(body)--    /** The rows the list shows, in order: header, blank, body, blank, description. */-    fun displayLines(description: String): List<String> = buildList {-        val headerRows = headerLines()-        addAll(headerRows)-        if (headerRows.isNotEmpty()) add("")-        addAll(bodyLines())-        if (description.isNotBlank()) {-            add("")-            addAll(splitLines("description: $description"))+    val headerLines: List<String> =+        if (headerLines.all(String::isBlank)) emptyList() else headerLines++    /** The rows the list shows - header, blank, body - as a view, not a copy. */+    val lines: List<String> = object : AbstractList<String>() {+        private val bodyStart =+            if ([email protected]()) 0 else [email protected] + 1++        override val size: Int get() = bodyStart + bodyLines.size++        override fun get(index: Int): String {+            val header = [email protected]+            return when {+                index < header.size -> header[index]+                index < bodyStart -> ""+                else -> bodyLines[index - bodyStart]+            }         }     } @@ -58,17 +54,15 @@ data class LogDocument(      * binder transaction limit that `ClipboardManager.setPrimaryClip` has to fit inside - going      * over it is a `TransactionTooLargeException`, not a truncated paste.      */-    fun clipText(description: String): ClipText {-        var sumSize = header.toByteArray(Charsets.UTF_8).size +-            description.toByteArray(Charsets.UTF_8).size+    fun clipText(): ClipText {+        var sumSize = headerLines.sumOf { utf8Length(it) + 1 }         var sumChars = 0         var bodyStartIndex = 0 -        val bodyLines = bodyLines()         for (i in bodyLines.indices.reversed()) {             val line = bodyLines[i]             sumChars += line.length + 1-            sumSize += line.toByteArray(Charsets.UTF_8).size + 1+            sumSize += utf8Length(line) + 1             if (sumSize > MAX_CLIP_BYTES) {                 bodyStartIndex = i + 1                 break@@ -78,12 +72,11 @@ data class LogDocument(         val sb = StringBuilder(sumChars + 1000)         sb.append("```\n") -        val headerRows = headerLines()-        for (line in headerRows) {+        for (line in headerLines) {             sb.append(line)             sb.append('\n')         }-        if (headerRows.size > 1) sb.append('\n')+        if (headerLines.size > 1) sb.append('\n')          if (bodyStartIndex != 0) sb.append("[[TRUNCATED]]\n") @@ -92,43 +85,28 @@ data class LogDocument(             sb.append('\n')         } -        appendDescription(sb, description)         sb.append("```\n")          return ClipText(sb.toString(), truncated = bodyStartIndex != 0)     }      /** The whole thing, unfenced and untruncated: what Save writes and what Share hands over. */-    fun snapshotText(description: String): String {-        val sb = StringBuilder()--        val headerRows = headerLines()-        for (line in headerRows) {-            sb.append(line)-            sb.append('\n')+    fun writeSnapshot(out: Appendable) {+        for (line in headerLines) {+            out.append(line)+            out.append('\n')         }-        if (headerRows.size > 1) sb.append('\n')+        if (headerLines.size > 1) out.append('\n') -        for (line in bodyLines()) {-            sb.append(line)-            sb.append('\n')+        for (line in bodyLines) {+            out.append(line)+            out.append('\n')         }--        appendDescription(sb, description)-        return sb.toString()-    }--    private fun appendDescription(sb: StringBuilder, description: String) {-        if (description.isBlank()) return-        sb.append("\ndescription: ")-        sb.append(description)-        sb.append('\n')     }      data class ClipText(val text: String, val truncated: Boolean)      companion object {-        private const val MAX_SIZE_FOR_COPY = 50_000         private const val MAX_CLIP_BYTES = 200_000          /**@@ -145,19 +123,36 @@ data class LogDocument(             trimToSize(title, 200) + ' ' + UUID.randomUUID().toString().substring(24) + ".txt"          /**-         * `String.split` the way `java.lang.String.split` does it, which is what the header/body-         * line counts were written against: trailing empty strings are dropped, so a body ending in-         * a newline does not gain a blank last row (and so "scroll to the last line" lands on the-         * last line).+         * Trailing empty strings are dropped, so a body ending in a newline does not gain a blank+         * last row (and so "scroll to the last line" lands on the last line).          */         internal fun splitLines(s: String): List<String> {-            if (s.isEmpty()) return listOf("")             val parts = s.split("\n")             var end = parts.size             while (end > 0 && parts[end - 1].isEmpty()) end--             return parts.subList(0, end)         } +        /** Counted rather than encoded: encoding every line just to measure it doubles the work. */+        private fun utf8Length(s: String): Int {+            var bytes = 0+            var i = 0+            while (i < s.length) {+                val c = s[i]+                bytes += when {+                    c.code < 0x80 -> 1+                    c.code < 0x800 -> 2+                    c.isHighSurrogate() && i + 1 < s.length && s[i + 1].isLowSurrogate() -> {+                        i+++                        4+                    }+                    else -> 3+                }+                i+++            }+            return bytes+        }+         /** [android.text.TextUtils.trimToSize], reimplemented so this file stays Android-free. */         private fun trimToSize(s: String, maxLength: Int): String {             if (s.length <= maxLength) return s
logviewer/src/main/java/com/vayunmathur/logviewer/intents/LogcatActivity.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/intents/LogcatActivity.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/intents/LogcatActivity.ktindex 3532fb1633..4c854ed96e 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/intents/LogcatActivity.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/intents/LogcatActivity.kt@@ -9,11 +9,12 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.logviewer.domain.LogDocument import com.vayunmathur.logviewer.domain.LogLevel import com.vayunmathur.logviewer.platform.ExtraAction+import com.vayunmathur.logviewer.platform.LogLoadResult import com.vayunmathur.logviewer.platform.LogViewerController import com.vayunmathur.logviewer.platform.LogViewerViewModel-import com.vayunmathur.logviewer.platform.LogcatActivityExtras import com.vayunmathur.logviewer.platform.LogcatFilters import com.vayunmathur.logviewer.platform.LogcatReader import com.vayunmathur.logviewer.ui.LogViewerPage@@ -26,8 +27,8 @@ import com.vayunmathur.logviewer.ui.LogViewerPage  * signed with the same key can open it. There is no launcher entry: the log is something another  * system surface sends the user to, not something to browse to.  *- * The whole activity is one snapshot of the log with one set of filters. Changing a filter starts- * another one - see [LogViewerController].+ * Changing a filter re-reads the log in this same window; the active filters live in the+ * ViewModel, so they survive rotation.  */ class LogcatActivity : ComponentActivity() { @@ -36,34 +37,20 @@ class LogcatActivity : ComponentActivity() {     // One instance, not one per recomposition of setContent's lambda.     private val actions by lazy { Actions() } +    private var targetPackage: String? = null+    private var isSystemUser = false+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState) -        val request = readRequest(intent)+        // Set by the framework for ACTION_PKG_LOGCAT, and by the error report's "Show log" button.+        targetPackage = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME)         // Read here rather than in the loader: a secondary user may see their own apps' logs but         // not the device log, and the answer must not depend on which thread asks.-        val isSystemUser = getSystemService(UserManager::class.java)?.isSystemUser == true-        val context: Context = applicationContext+        isSystemUser = getSystemService(UserManager::class.java)?.isSystemUser == true -        viewModel.start(-            loader = { LogcatReader.read(context, request) },-            chrome = {-                LogViewerViewModel.Chrome(-                    showReportButton = false,-                    extraActions =-                        if (request.targetPackage != null && isSystemUser) {-                            listOf(ExtraAction.ShowSystemLog)-                        } else {-                            emptyList()-                        },-                    logcat = LogcatFilters(-                        buffers = request.buffers,-                        level = request.level,-                        filterRegex = request.filterRegex,-                    ),-                )-            },-        )+        val initial = LogcatFilters(LogcatReader.DEFAULT_BUFFERS, LogLevel.Verbose, filterRegex = "")+        viewModel.start(loader = loader(initial), chrome = chrome(initial))          enableEdgeToEdge()         setContent {@@ -77,18 +64,40 @@ class LogcatActivity : ComponentActivity() {         }     } -    private fun readRequest(intent: Intent): LogcatReader.Request = LogcatReader.Request(-        // Set by the framework for ACTION_PKG_LOGCAT, and by our own "Show log" button.-        targetPackage = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME),-        buffers = intent.getStringArrayListExtra(LogcatActivityExtras.LOG_BUFFERS)-            ?: LogcatReader.DEFAULT_BUFFERS,-        level = LogLevel.ofPriority(-            intent.getIntExtra(LogcatActivityExtras.LOG_LEVEL, LogLevel.Verbose.priority)-        ),-        filterRegex = intent.getStringExtra(LogcatActivityExtras.FILTER_REGEX).orEmpty(),-    )+    private fun loader(filters: LogcatFilters): suspend () -> LogLoadResult {+        val context: Context = applicationContext+        val request = LogcatReader.Request(+            targetPackage = targetPackage,+            buffers = filters.buffers,+            level = filters.level,+            filterRegex = filters.filterRegex,+        )+        return { LogcatReader.read(context, request) }+    }++    private fun chrome(filters: LogcatFilters): suspend (LogDocument) -> LogViewerViewModel.Chrome = {+        LogViewerViewModel.Chrome(+            extraActions =+                if (targetPackage != null && isSystemUser) listOf(ExtraAction.ShowSystemLog)+                else emptyList(),+            logcat = filters,+        )+    }++    private fun reload(edit: LogcatFilters.() -> LogcatFilters) {+        val current = viewModel.state.value.logcat ?: return+        val next = current.edit()+        if (next == current) return+        viewModel.reload(next, loader(next), chrome(next))+    }      private inner class Actions : LogViewerController(this@LogcatActivity, viewModel) {+        override fun setBuffers(buffers: List<String>) = reload { copy(buffers = buffers) }++        override fun setLevel(level: LogLevel) = reload { copy(level = level) }++        override fun setFilter(regex: String) = reload { copy(filterRegex = regex) }+         override fun perform(action: ExtraAction) {             if (action != ExtraAction.ShowSystemLog) return             // No extras: the system log with the default buffers and no filter.
logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerController.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerController.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerController.ktindex aa3484c723..8b332b16c8 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerController.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerController.kt@@ -6,20 +6,16 @@ import android.content.Intent import android.net.Uri import androidx.activity.ComponentActivity import androidx.core.net.toUri+import androidx.lifecycle.lifecycleScope import com.vayunmathur.library.util.AppMessages import com.vayunmathur.logviewer.R import com.vayunmathur.logviewer.domain.LogDocument import com.vayunmathur.logviewer.domain.LogLevel-import com.vayunmathur.logviewer.provider.BlobProvider+import kotlinx.coroutines.launch  /**  * The half of [LogViewerActions] that needs an Activity: the clipboard, the share sheet, and  * starting the next screen.- *- * Changing a logcat filter starts a *new* activity carrying the edited intent rather than reloading- * in place. That is what makes Back step through the filters the user tried, and with- * `documentLaunchMode="always"` each one is its own entry in Recents - so two logs can be compared- * side by side. Reloading in place would quietly lose both.  */ internal open class LogViewerController(     private val activity: ComponentActivity,@@ -38,16 +34,17 @@ internal open class LogViewerController(     }      override fun share() {-        val bytes = viewModel.snapshotBytes() ?: return         val fileName = viewModel.state.value.snapshotFileName-        val uri = BlobProvider.getUri(fileName, bytes)-        val send = Intent(Intent.ACTION_SEND).apply {-            putExtra(Intent.EXTRA_SUBJECT, fileName)-            type = LogDocument.MIME_TYPE-            putExtra(Intent.EXTRA_STREAM, uri)-            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+        activity.lifecycleScope.launch {+            val uri = viewModel.shareUri() ?: return@launch+            val send = Intent(Intent.ACTION_SEND).apply {+                putExtra(Intent.EXTRA_SUBJECT, fileName)+                type = LogDocument.MIME_TYPE+                putExtra(Intent.EXTRA_STREAM, uri)+                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+            }+            activity.startActivity(Intent.createChooser(send, fileName))         }-        activity.startActivity(Intent.createChooser(send, fileName))     }      /**@@ -61,23 +58,15 @@ internal open class LogViewerController(      override fun save(uri: Uri) = viewModel.save(uri) -    override fun setDescription(description: String) = viewModel.setDescription(description)-     override fun zoom(factor: Float) = viewModel.zoom(factor) -    override fun setBuffers(buffers: List<String>) = relaunch {-        putStringArrayListExtra(LogcatActivityExtras.LOG_BUFFERS, ArrayList(buffers))-    }+    /** The filter and extra actions do nothing by default; each entry point overrides what it offers. */+    override fun setBuffers(buffers: List<String>) = Unit -    override fun setLevel(level: LogLevel) = relaunch {-        putExtra(LogcatActivityExtras.LOG_LEVEL, level.priority)-    }+    override fun setLevel(level: LogLevel) = Unit -    override fun setFilter(regex: String) = relaunch {-        putExtra(LogcatActivityExtras.FILTER_REGEX, regex)-    }+    override fun setFilter(regex: String) = Unit -    /** Nothing by default; each entry point overrides the actions it actually offers. */     override fun perform(action: ExtraAction) = Unit      override fun dismissStackTrace() = viewModel.dismissStackTrace()@@ -89,9 +78,6 @@ internal open class LogViewerController(      protected fun start(intent: Intent) = activity.startActivity(intent) -    private fun relaunch(edit: Intent.() -> Unit) {-        activity.startActivity(Intent(activity.intent).apply(edit))-    }      private fun copyToClipboard(label: CharSequence?, text: String) {         activity.getSystemService(ClipboardManager::class.java)@@ -103,16 +89,3 @@ internal open class LogViewerController(     } } -/**- * Extras the logcat screen sends to itself.- *- * Unlike the names in `LogViewerIntents` these are private to the app - nothing outside it produces- * them - so they are package-qualified to keep them out of anyone else's way.- */-internal object LogcatActivityExtras {-    private const val PREFIX = "com.vayunmathur.logviewer.LogcatActivity"--    const val LOG_BUFFERS = "$PREFIX.LOG_BUFFERS"-    const val LOG_LEVEL = "$PREFIX.LOG_LEVEL"-    const val FILTER_REGEX = "$PREFIX.FILTER_REGEX"-}
logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerUiContract.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerUiContract.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerUiContract.ktindex 9fa70d4337..2b627d8d18 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerUiContract.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerUiContract.kt@@ -15,6 +15,8 @@ import com.vayunmathur.logviewer.domain.LogLevel  */ internal data class LogViewerUiState(     val loading: Boolean = true,+    /** A filter change is re-reading the log; the previous one stays on screen meanwhile. */+    val refreshing: Boolean = false,     /**      * Set when the log could not be produced. A null [unavailableMessageRes] with [loading] false      * means close the window silently; a non-null one means say why first.@@ -24,15 +26,12 @@ internal data class LogViewerUiState(     val title: String = "",     /** The app the log is about, if any: what "Show log" opens. */     val sourcePackage: String? = null,-    /** Header, body and description already flattened into the rows the list shows. */+    /** Header and body already flattened into the rows the list shows. */     val lines: List<String> = emptyList(),     val kind: LogKind = LogKind.ErrorReport,     val fontSizeSp: Float = LogKind.ErrorReport.initialFontSizeSp,-    /** False for a log too large to fit in a clipboard transaction: Save replaces Copy. */-    val canCopy: Boolean = false,-    /** True for a report the sender wants filed: Report replaces Share. */+    /** True for a report the sender wants filed: a Report button joins the bottom row. */     val showReportButton: Boolean = false,-    val description: String = "",     val snapshotFileName: String = "",     val logcat: LogcatFilters? = null,     val extraActions: List<ExtraAction> = emptyList(),@@ -65,7 +64,6 @@ internal interface LogViewerActions {     fun share()     fun report()     fun save(uri: Uri)-    fun setDescription(description: String)      /** Pinch-to-zoom; [factor] is the incremental scale since the last gesture event. */     fun zoom(factor: Float)
logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerViewModel.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerViewModel.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerViewModel.ktindex faf1c4ae81..a4f1233ae8 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerViewModel.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogViewerViewModel.kt@@ -7,7 +7,9 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.library.util.AppMessages import com.vayunmathur.logviewer.R import com.vayunmathur.logviewer.domain.LogDocument+import com.vayunmathur.logviewer.provider.BlobProvider import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -18,8 +20,7 @@ import java.io.IOException import java.io.PrintStream  /**- * Holds the loaded log and the parts of the screen the user changes: the description and the font- * size.+ * Holds the loaded log and the one part of the screen the user changes: the font size.  *  * The app this replaces kept these in a process-wide `LruCache` keyed by a UUID it stashed in the  * saved instance state, because a plain `Activity` loses its fields on rotation. A ViewModel is@@ -36,6 +37,7 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a      private var document: LogDocument? = null     private var started = false+    private var loadJob: Job? = null      /** The parts of the chrome that depend on what was actually loaded. */     data class Chrome(@@ -47,7 +49,25 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a     fun start(loader: suspend () -> LogLoadResult, chrome: suspend (LogDocument) -> Chrome) {         if (started) return         started = true-        viewModelScope.launch {+        load(loader, chrome)+    }++    /**+     * Re-reads logcat with new [filters] in place. The current log stays on screen under a progress+     * bar until the new one arrives, and a newer change cancels one still in flight.+     */+    fun reload(+        filters: LogcatFilters,+        loader: suspend () -> LogLoadResult,+        chrome: suspend (LogDocument) -> Chrome,+    ) {+        _state.update { it.copy(logcat = filters, refreshing = true) }+        load(loader, chrome)+    }++    private fun load(loader: suspend () -> LogLoadResult, chrome: suspend (LogDocument) -> Chrome) {+        loadJob?.cancel()+        loadJob = viewModelScope.launch {             // Both run on IO: `chrome` decides whether "More info" applies, which means reading             // /data/tombstones.             val outcome = withContext(Dispatchers.IO) {@@ -60,6 +80,7 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a                 is LogLoadResult.Unavailable -> _state.update {                     it.copy(                         loading = false,+                        refreshing = false,                         unavailable = true,                         unavailableMessageRes = result.messageRes,                     )@@ -69,31 +90,27 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a                     val loaded = result.document                     document = loaded                     val resolved = outcome.second ?: Chrome()+                    val previous = _state.value                     _state.value = LogViewerUiState(                         loading = false,                         title = loaded.title,                         sourcePackage = loaded.sourcePackage,-                        lines = loaded.displayLines(""),+                        lines = loaded.lines,                         kind = loaded.kind,-                        fontSizeSp = loaded.kind.initialFontSizeSp,-                        canCopy = loaded.canCopy,+                        // A reload keeps the size the user pinched to.+                        fontSizeSp =+                            if (previous.loading) loaded.kind.initialFontSizeSp else previous.fontSizeSp,                         showReportButton = resolved.showReportButton,                         snapshotFileName = LogDocument.snapshotFileName(loaded.title),                         logcat = resolved.logcat,                         extraActions = resolved.extraActions,+                        stackTrace = previous.stackTrace,                     )                 }             }         }     } -    fun setDescription(description: String) {-        val loaded = document ?: return-        _state.update {-            it.copy(description = description, lines = loaded.displayLines(description))-        }-    }-     fun zoom(factor: Float) {         _state.update { it.copy(fontSizeSp = (it.fontSizeSp * factor).coerceIn(MIN_SP, MAX_SP)) }     }@@ -101,10 +118,18 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a     fun dismissStackTrace() = _state.update { it.copy(stackTrace = null) }      /** The clipboard text, or null if nothing is loaded. Truncation is reported by the caller. */-    fun clipText(): LogDocument.ClipText? = document?.clipText(_state.value.description)+    fun clipText(): LogDocument.ClipText? = document?.clipText() -    fun snapshotBytes(): ByteArray? =-        document?.snapshotText(_state.value.description)?.toByteArray(Charsets.UTF_8)+    /** Off the main thread: compressing a multi-megabyte log is long enough to drop frames. */+    suspend fun shareUri(): Uri? {+        val loaded = document ?: return null+        val fileName = _state.value.snapshotFileName+        return withContext(Dispatchers.Default) {+            BlobProvider.getUri(fileName) { out ->+                out.bufferedWriter(Charsets.UTF_8).use { loaded.writeSnapshot(it) }+            }+        }+    }      /**      * Writes the log to the document the user picked.@@ -113,7 +138,7 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a      * because the interesting part of "could not write" is which exception it was.      */     fun save(uri: Uri) {-        val bytes = snapshotBytes() ?: return+        val loaded = document ?: return         val fileName = _state.value.snapshotFileName         val context = getApplication<Application>()         viewModelScope.launch {@@ -121,7 +146,7 @@ internal class LogViewerViewModel(application: Application) : AndroidViewModel(a                 try {                     val stream = context.contentResolver.openOutputStream(uri)                         ?: return@withContext OpenFailed-                    stream.use { it.write(bytes) }+                    stream.bufferedWriter(Charsets.UTF_8).use { loaded.writeSnapshot(it) }                     null                 } catch (e: IOException) {                     e
logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.ktindex 7f7b4b9fd7..103a322fd3 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/platform/LogcatReader.kt@@ -21,11 +21,12 @@ import java.io.IOException  * anything but this process's own lines.  *  * `-d` means dump and exit, so this is a snapshot, not a stream - the same as the app it replaces.- * Re-reading is a new activity, which is what gives the filter controls a back stack.+ * Re-reading for new filters is another call to this, in the same window.  */ internal object LogcatReader {      private const val TAG = "LogcatReader"+    private const val INITIAL_LINE_CAPACITY = 16_384      val DEFAULT_BUFFERS: List<String> = listOf("main", "system", "crash", "events", "kernel") @@ -79,11 +80,14 @@ internal object LogcatReader {          Log.debug(TAG, "command: " + command.joinToString(" ")) -        val logcatBytes = try {+        // Parsed as it streams in, so the raw dump is never held whole alongside its lines.+        val body = ArrayList<String>(INITIAL_LINE_CAPACITY)+        try {             val process = ProcessBuilder(command).start()-            val bytes = process.inputStream.use { it.readBytes() }+            process.inputStream.bufferedReader(Charsets.UTF_8).useLines { lines ->+                for (line in lines) body += stripUtcOffset(line)+            }             Log.debug(TAG, "logcat return code: " + process.waitFor())-            bytes         } catch (e: IOException) {             Log.error(TAG, "logcat failed", e)             return LogLoadResult.Unavailable()@@ -91,6 +95,8 @@ internal object LogcatReader {             Log.error(TAG, "logcat interrupted", e)             return LogLoadResult.Unavailable()         }+        while (body.isNotEmpty() && body[body.lastIndex].isEmpty()) body.removeAt(body.lastIndex)+        body.trimToSize()          val header = mutableListOf("type: logcat", "osVersion: ${Build.FINGERPRINT}")         ReportHeaders.addDeviceLines(context, header)@@ -104,8 +110,8 @@ internal object LogcatReader {                 kind = LogKind.Logcat,                 sourcePackage = request.targetPackage,                 title = buildTitle(context, request),-                header = header.joinToString("\n"),-                body = stripUtcOffsets(String(logcatBytes, Charsets.UTF_8)),+                headerLines = header,+                bodyLines = body,             )         )     }@@ -142,12 +148,5 @@ internal object LogcatReader {      * `--format=UTC` stamps every single line with `+0000`, which is the same on all of them and      * costs six columns of a screen that is already too narrow.      */-    private fun stripUtcOffsets(text: String): String {-        val sb = StringBuilder(text.length)-        for (line in text.split("\n")) {-            sb.append(line.replaceFirst(" +0000", ""))-            sb.append('\n')-        }-        return sb.toString()-    }+    private fun stripUtcOffset(line: String): String = line.replaceFirst(" +0000", "") }
logviewer/src/main/java/com/vayunmathur/logviewer/provider/BlobProvider.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/provider/BlobProvider.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/provider/BlobProvider.ktindex 6932f7d899..7cd0c70908 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/provider/BlobProvider.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/provider/BlobProvider.kt@@ -16,7 +16,9 @@ import com.vayunmathur.logviewer.domain.LogDocument import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.FileNotFoundException+import java.io.FilterOutputStream import java.io.IOException+import java.io.OutputStream import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream @@ -124,19 +126,34 @@ class BlobProvider : ContentProvider(), ContentProvider.PipeDataWriter<ByteArray             override fun sizeOf(key: Uri, value: Entry): Int = value.gzipped.size         } -        /** Registers [bytes] under a Uri named [blobName] and returns that Uri. */-        fun getUri(blobName: String, bytes: ByteArray): Uri {+        /**+         * Registers whatever [write] produces under a Uri named [blobName] and returns that Uri.+         * Compressed as it is written, so the uncompressed log never exists as one array.+         */+        fun getUri(blobName: String, write: (OutputStream) -> Unit): Uri {             val uri = Uri.Builder()                 .scheme(ContentResolver.SCHEME_CONTENT)                 .authority(AUTHORITY)                 .path(blobName)                 .build() -            val compressed = ByteArrayOutputStream(bytes.size).also { out ->-                GZIPOutputStream(out).use { it.write(bytes) }-            }.toByteArray()+            val compressed = ByteArrayOutputStream()+            var size = 0+            GZIPOutputStream(compressed).use { gzip ->+                write(object : FilterOutputStream(gzip) {+                    override fun write(b: Int) {+                        out.write(b)+                        size+++                    }++                    override fun write(b: ByteArray, off: Int, len: Int) {+                        out.write(b, off, len)+                        size += len+                    }+                })+            } -            synchronized(entries) { entries.put(uri, Entry(compressed, bytes.size)) }+            synchronized(entries) { entries.put(uri, Entry(compressed.toByteArray(), size)) }             return uri         }     }
logviewer/src/main/java/com/vayunmathur/logviewer/ui/LogViewerScreen.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/LogViewerScreen.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/LogViewerScreen.ktindex 1e280666c2..68a596299c 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/LogViewerScreen.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/LogViewerScreen.kt@@ -3,7 +3,9 @@ package com.vayunmathur.logviewer.ui import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize@@ -28,30 +30,36 @@ import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.ErrorState+import com.vayunmathur.library.ui.FloatingActionButtonMenu+import com.vayunmathur.library.ui.FloatingActionButtonMenuItem import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconDescription-import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconSave import com.vayunmathur.library.ui.IconSearch-import com.vayunmathur.library.ui.IconTune+import com.vayunmathur.library.ui.IconShare+import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OverflowMenu+import com.vayunmathur.library.ui.MultiSelectDropdown+import com.vayunmathur.library.ui.SelectDropdown import com.vayunmathur.library.ui.SnackbarHost import com.vayunmathur.library.ui.SnackbarHostState import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.ToggleFloatingActionButton import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.library.util.AppMessages import com.vayunmathur.logviewer.R import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.logviewer.domain.LogDocument+import com.vayunmathur.logviewer.domain.LogLevel import com.vayunmathur.logviewer.platform.ExtraAction import com.vayunmathur.logviewer.platform.LogViewerActions import com.vayunmathur.logviewer.platform.LogViewerUiState+import com.vayunmathur.logviewer.platform.LogcatReader import com.vayunmathur.logviewer.ui.components.LogLineList-import com.vayunmathur.logviewer.ui.dialogs.LogBuffersDialog-import com.vayunmathur.logviewer.ui.dialogs.LogLevelDialog import com.vayunmathur.logviewer.ui.dialogs.StackTraceDialog import com.vayunmathur.logviewer.ui.dialogs.TextInputDialog @@ -61,10 +69,9 @@ import com.vayunmathur.logviewer.ui.dialogs.TextInputDialog  * Stateless, so both entry points render it from their own [LogViewerUiState] and nothing about a  * crash report or a logcat dump is baked into the layout.  *- * The bottom row is a pair of either/or buttons, which is inherited and is a real decision worth- * keeping. Copy becomes Save once the log is too large for a clipboard transaction, so the button- * offered is always one that will work; Share becomes Report when the sender says the report is- * worth filing, which puts the tracker one tap away at the moment the user is looking at the crash.+ * Copy, Share and Save live behind one share FAB. The bottom row is left for the actions specific+ * to what is on screen: Report when the sender says the report is worth filing, and the jumps to a+ * related log.  */ @Composable internal fun LogViewerScreen(state: LogViewerUiState, actions: LogViewerActions) {@@ -76,10 +83,7 @@ internal fun LogViewerScreen(state: LogViewerUiState, actions: LogViewerActions)     // dialog over it (see the scaffold content below).     val expanded = isExpandedWidth() -    var showDescription by remember { mutableStateOf(false) }     var showFilter by remember { mutableStateOf(false) }-    var showLevel by remember { mutableStateOf(false) }-    var showBuffers by remember { mutableStateOf(false) }      // This app has no MainNavigation to drain AppMessages, so the one screen it has does it.     LaunchedEffect(snackbarHostState) {@@ -92,16 +96,10 @@ internal fun LogViewerScreen(state: LogViewerUiState, actions: LogViewerActions)         ActivityResultContracts.CreateDocument(LogDocument.MIME_TYPE)     ) { uri -> if (uri != null) actions.save(uri) } -    // A log is read from the end, so that is where it opens. Only for logcat: a stack trace is read-    // from the top.-    LaunchedEffect(state.loading) {-        if (!state.loading && state.kind.scrollToBottom && state.lines.isNotEmpty()) {-            listState.scrollToItem(state.lines.lastIndex)-        }-    }-    // A description is appended to the end, and writing one you cannot see is pointless.-    LaunchedEffect(state.description) {-        if (state.description.isNotEmpty() && state.lines.isNotEmpty()) {+    // A log is read from the end, so that is where it opens, and where a filter change lands. Only+    // for logcat: a stack trace is read from the top.+    LaunchedEffect(state.lines) {+        if (state.kind.scrollToBottom && state.lines.isNotEmpty()) {             listState.scrollToItem(state.lines.lastIndex)         }     }@@ -112,144 +110,125 @@ internal fun LogViewerScreen(state: LogViewerUiState, actions: LogViewerActions)         snackbarHost = { SnackbarHost(snackbarHostState) },         actions = {             if (!state.loading && !state.unavailable) {-                IconButton(onClick = { showDescription = true }) { IconDescription() }-                if (state.logcat != null) {+                val logcat = state.logcat+                if (logcat != null) {                     IconButton(onClick = { showFilter = true }) { IconSearch() }-                    IconButton(onClick = { showLevel = true }) { IconTune() }-                }-                if (state.showReportButton || state.canCopy || state.logcat != null) {-                    // OverflowMenu defaults to IconMenu(), a hamburger. This is an overflow, not a-                    // drawer.-                    OverflowMenu(icon = { IconMoreVert() }) {-                        // Share and Save appear here only when the bottom row gave their slot to-                        // Report and Copy - never twice.-                        if (state.showReportButton) {-                            Item(stringResource(UiR.string.share)) { actions.share() }-                        }-                        if (state.canCopy) {-                            Item(stringResource(UiR.string.save)) {-                                save.launch(state.snapshotFileName)-                            }-                        }-                        if (state.logcat != null) {-                            Item(stringResource(R.string.log_buffers)) { showBuffers = true }-                        }-                    }+                    SelectDropdown(+                        label = logcat.level.letter.toString(),+                        options = LogLevel.entries,+                        selected = logcat.level,+                        itemLabel = { stringResource(it.labelRes) },+                        onSelect = actions::setLevel,+                    )+                    MultiSelectDropdown(+                        label = logcat.buffers.joinToString("") { it.take(1).uppercase() },+                        options = LogcatReader.ALL_BUFFERS,+                        selected = logcat.buffers,+                        itemLabel = { it },+                        onApply = actions::setBuffers,+                    )                 }             }         },-        bottomBar = {+        floatingActionButton = {             if (!state.loading && !state.unavailable) {-                BottomActions(state, actions, onSave = { save.launch(state.snapshotFileName) })+                ShareFab(+                    onCopy = actions::copy,+                    onShare = actions::share,+                    onSave = { save.launch(state.snapshotFileName) },+                )+            }+        },+        bottomBar = {+            if (!state.loading && !state.unavailable &&+                (state.showReportButton || state.extraActions.isNotEmpty())+            ) {+                BottomActions(state, actions)             }         },-    ) { padding ->-        when {-            state.loading -> LoadingState(Modifier.padding(padding))+    ) { scaffoldPadding ->+        // Room under the last line for the FAB, so the newest log line is never hidden behind it.+        val padding = PaddingValues(+            top = scaffoldPadding.calculateTopPadding(),+            bottom = scaffoldPadding.calculateBottomPadding() + FAB_CLEARANCE,+        )+        Box(Modifier.fillMaxSize()) {+            when {+                state.loading -> LoadingState(Modifier.padding(padding))++                state.unavailable -> {+                    val messageRes = state.unavailableMessageRes+                    // A failure with no message is already closing the window (see LogViewerPage).+                    // Rendering the fallback text here would flash the wrong reason on the way out.+                    if (messageRes != null) {+                        ErrorState(+                            title = stringResource(messageRes),+                            modifier = Modifier.padding(padding),+                        )+                    }+                } -            state.unavailable -> {-                val messageRes = state.unavailableMessageRes-                // A failure with no message is already closing the window (see LogViewerPage).-                // Rendering the fallback text here would flash the wrong reason on the way out.-                if (messageRes != null) {-                    ErrorState(-                        title = stringResource(messageRes),-                        modifier = Modifier.padding(padding),+                // Expanded windows (large tablets, desktop) put the log lines and the+                // "unable to save" stack trace side by side instead of stacking a+                // modal dialog over the log — there is room for both, and the trace+                // explains the log the user is already looking at.+                expanded && state.stackTrace != null -> Row(modifier = Modifier.fillMaxSize().padding(padding)) {+                    LogLineList(+                        lines = state.lines,+                        kind = state.kind,+                        fontSizeSp = state.fontSizeSp,+                        listState = listState,+                        contentPadding = PaddingValues(0.dp),+                        onZoom = actions::zoom,+                        // The 16dp gutter the app being replaced put around its whole layout. It stays on+                        // the list rather than the window so the top bar and the snackbar still go+                        // edge to edge.+                        modifier = Modifier.weight(1f).fillMaxHeight().padding(horizontal = 16.dp),+                    )+                    StackTraceSidePanel(+                        stackTrace = state.stackTrace,+                        onCopy = actions::copyStackTrace,+                        onDismiss = actions::dismissStackTrace,+                        modifier = Modifier.fillMaxWidth(0.4f).fillMaxHeight(),                     )                 }-            } -            // Expanded windows (large tablets, desktop) put the log lines and the-            // "unable to save" stack trace side by side instead of stacking a-            // modal dialog over the log — there is room for both, and the trace-            // explains the log the user is already looking at.-            expanded && state.stackTrace != null -> Row(modifier = Modifier.fillMaxSize().padding(padding)) {-                LogLineList(+                else -> LogLineList(                     lines = state.lines,                     kind = state.kind,                     fontSizeSp = state.fontSizeSp,                     listState = listState,-                    contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp),+                    contentPadding = padding,                     onZoom = actions::zoom,                     // The 16dp gutter the app being replaced put around its whole layout. It stays on                     // the list rather than the window so the top bar and the snackbar still go                     // edge to edge.-                    modifier = Modifier.weight(1f).fillMaxHeight().padding(horizontal = 16.dp),+                    modifier = Modifier.padding(horizontal = 16.dp),                 )-                StackTraceSidePanel(-                    stackTrace = state.stackTrace,-                    onCopy = actions::copyStackTrace,-                    onDismiss = actions::dismissStackTrace,-                    modifier = Modifier.fillMaxWidth(0.4f).fillMaxHeight(),+            }+            if (state.refreshing) {+                LinearProgressIndicator(+                    Modifier.fillMaxWidth().padding(top = scaffoldPadding.calculateTopPadding())                 )             }--            else -> LogLineList(-                lines = state.lines,-                kind = state.kind,-                fontSizeSp = state.fontSizeSp,-                listState = listState,-                contentPadding = padding,-                onZoom = actions::zoom,-                // The 16dp gutter the app being replaced put around its whole layout. It stays on-                // the list rather than the window so the top bar and the snackbar still go-                // edge to edge.-                modifier = Modifier.padding(horizontal = 16.dp),-            )         }     } -    if (showDescription) {-        val titleRes =-            if (state.description.isEmpty()) R.string.add_description-            else R.string.update_description+    val logcat = state.logcat+    if (logcat != null && showFilter) {         TextInputDialog(-            title = stringResource(titleRes),-            initialText = state.description,+            title = stringResource(R.string.set_filter),+            initialText = logcat.filterRegex,             onConfirm = {-                actions.setDescription(it.trim())-                showDescription = false+                showFilter = false+                actions.setFilter(it)             },-            onDismiss = { showDescription = false },+            onDismiss = { showFilter = false },+            singleLine = true,+            hint = stringResource(R.string.set_filter_editor_hint),         )     } -    val logcat = state.logcat-    if (logcat != null) {-        if (showFilter) {-            TextInputDialog(-                title = stringResource(R.string.set_filter),-                initialText = logcat.filterRegex,-                onConfirm = {-                    showFilter = false-                    // Applying an empty filter to an already-unfiltered log would be a new activity-                    // showing the same thing.-                    if (it.isNotEmpty() || logcat.filterRegex.isNotEmpty()) actions.setFilter(it)-                },-                onDismiss = { showFilter = false },-                singleLine = true,-                hint = stringResource(R.string.set_filter_editor_hint),-            )-        }-        if (showLevel) {-            LogLevelDialog(-                current = logcat.level,-                onSelect = {-                    showLevel = false-                    actions.setLevel(it)-                },-                onDismiss = { showLevel = false },-            )-        }-        if (showBuffers) {-            LogBuffersDialog(-                current = logcat.buffers,-                onApply = actions::setBuffers,-                onDismiss = { showBuffers = false },-            )-        }-    }-     val stackTrace = state.stackTrace     // On expanded widths the trace is already showing in the side panel next to     // the log; the dialog is only for compact windows where there is no room.@@ -299,24 +278,13 @@ private fun StackTraceSidePanel( }  @Composable-private fun BottomActions(-    state: LogViewerUiState,-    actions: LogViewerActions,-    onSave: () -> Unit,-) {+private fun BottomActions(state: LogViewerUiState, actions: LogViewerActions) {     Row(         modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(16.dp),         horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),     ) {-        if (state.canCopy) {-            Button(onClick = actions::copy) { Text(stringResource(UiR.string.copy)) }-        } else {-            Button(onClick = onSave) { Text(stringResource(UiR.string.save)) }-        }         if (state.showReportButton) {             Button(onClick = actions::report) { Text(stringResource(R.string.action_report)) }-        } else {-            Button(onClick = actions::share) { Text(stringResource(UiR.string.share)) }         }         for (extra in state.extraActions) {             Button(onClick = { actions.perform(extra) }) { Text(stringResource(extra.labelRes)) }@@ -324,6 +292,48 @@ private fun BottomActions(     } } +private val FAB_CLEARANCE = 88.dp++/** Copy, Share and Save, opening upward from one share FAB. */+@Composable+private fun ShareFab(onCopy: () -> Unit, onShare: () -> Unit, onSave: () -> Unit) {+    var open by remember { mutableStateOf(false) }+    FloatingActionButtonMenu(+        expanded = open,+        button = {+            ToggleFloatingActionButton(checked = open, onCheckedChange = { open = it }) {+                if (open) IconClose() else IconShare()+            }+        },+    ) {+        FloatingActionButtonMenuItem(+            onClick = { open = false; onCopy() },+            text = { Text(stringResource(UiR.string.copy)) },+            icon = { IconCopy() },+        )+        FloatingActionButtonMenuItem(+            onClick = { open = false; onShare() },+            text = { Text(stringResource(UiR.string.share)) },+            icon = { IconShare() },+        )+        FloatingActionButtonMenuItem(+            onClick = { open = false; onSave() },+            text = { Text(stringResource(UiR.string.save)) },+            icon = { IconSave() },+        )+    }+}++private val LogLevel.labelRes: Int+    get() = when (this) {+        LogLevel.Verbose -> R.string.log_level_verbose+        LogLevel.Debug -> R.string.log_level_debug+        LogLevel.Info -> R.string.log_level_info+        LogLevel.Warn -> R.string.log_level_warn+        LogLevel.Error -> R.string.log_level_error+        LogLevel.Assert -> R.string.log_level_assert+    }+ private val ExtraAction.labelRes: Int     get() = when (this) {         ExtraAction.MoreInfo -> R.string.action_more_info
logviewer/src/main/java/com/vayunmathur/logviewer/ui/components/LogLineList.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/components/LogLineList.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/components/LogLineList.ktindex 563ede82d1..def60995c1 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/components/LogLineList.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/components/LogLineList.kt@@ -43,7 +43,7 @@ internal fun LogLineList(         contentPadding = contentPadding,         modifier = modifier.fillMaxSize().pinchToZoom(onZoom),     ) {-        items(count = lines.size, key = { it }) { index ->+        items(count = lines.size) { index ->             Text(                 text = kind.displayLine(lines[index]),                 fontFamily = FontFamily.Monospace,
logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogBuffersDialog.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogBuffersDialog.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogBuffersDialog.ktdeleted file mode 100644index 571e23c0d5..0000000000--- a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogBuffersDialog.kt+++ /dev/null@@ -1,40 +0,0 @@-package com.vayunmathur.logviewer.ui.dialogs--import androidx.compose.runtime.Composable-import androidx.compose.ui.res.stringResource-import com.vayunmathur.library.ui.AddToListDialog-import com.vayunmathur.logviewer.R-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.logviewer.platform.LogcatReader--/**- * Picks which of the kernel and framework ring buffers to read.- *- * The shared [AddToListDialog] is exactly this shape - a checkbox list staged locally and applied- * on OK - so it is reused rather than rebuilt, with the "create new" half left out.- *- * An empty selection dismisses without applying: `logcat --buffer=` with nothing after it is an- * error, and silently doing nothing is what the dialog this replaces did.- */-@Composable-internal fun LogBuffersDialog(-    current: List<String>,-    onApply: (List<String>) -> Unit,-    onDismiss: () -> Unit,-) {-    AddToListDialog(-        title = stringResource(R.string.log_buffers),-        options = LogcatReader.ALL_BUFFERS,-        itemLabel = { it },-        confirmLabel = stringResource(UiR.string.apply),-        dismissLabel = stringResource(UiR.string.cancel),-        onConfirm = { selected ->-            onDismiss()-            // Re-filtered rather than used as-is: the dialog hands back a Set, and the buffer order-            // shows up in both the `buffers:` header line and the title's "MSCEK" suffix.-            if (selected.isNotEmpty()) onApply(LogcatReader.ALL_BUFFERS.filter { it in selected })-        },-        onDismiss = onDismiss,-        initiallyChecked = { it in current },-    )-}
logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogLevelDialog.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogLevelDialog.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogLevelDialog.ktdeleted file mode 100644index ee8d2f95b7..0000000000--- a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/LogLevelDialog.kt+++ /dev/null@@ -1,62 +0,0 @@-package com.vayunmathur.logviewer.ui.dialogs--import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Column-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import com.vayunmathur.library.ui.AlertDialog-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.RadioButton-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.logviewer.R-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.logviewer.domain.LogLevel--/**- * Picks the minimum severity to show.- *- * Choosing applies immediately - there is no Apply button, matching the single-choice list this- * replaces. Applying means re-running `logcat` with a new `*:X` argument, so it is a new screen- * rather than a filter over what is already loaded.- *- * The labels are translated, but the value they select is not: see [LogLevel].- */-@Composable-internal fun LogLevelDialog(-    current: LogLevel,-    onSelect: (LogLevel) -> Unit,-    onDismiss: () -> Unit,-) {-    AlertDialog(-        onDismissRequest = onDismiss,-        title = { Text(stringResource(R.string.log_level)) },-        text = {-            Column {-                for (level in LogLevel.entries) {-                    ListItem(-                        content = { Text(stringResource(level.labelRes)) },-                        leadingContent = {-                            RadioButton(selected = level == current, onClick = { onSelect(level) })-                        },-                        modifier = Modifier.clickable { onSelect(level) },-                    )-                }-            }-        },-        confirmButton = {-            TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }-        },-    )-}--private val LogLevel.labelRes: Int-    get() = when (this) {-        LogLevel.Verbose -> R.string.log_level_verbose-        LogLevel.Debug -> R.string.log_level_debug-        LogLevel.Info -> R.string.log_level_info-        LogLevel.Warn -> R.string.log_level_warn-        LogLevel.Error -> R.string.log_level_error-        LogLevel.Assert -> R.string.log_level_assert-    }
logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/TextInputDialog.kt
diff --git a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/TextInputDialog.kt b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/TextInputDialog.ktindex 09076328a3..95bfdcc597 100644--- a/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/TextInputDialog.kt+++ b/logviewer/src/main/java/com/vayunmathur/logviewer/ui/dialogs/TextInputDialog.kt@@ -23,7 +23,7 @@ import com.vayunmathur.logviewer.R import com.vayunmathur.library.ui.R as UiR  /**- * A dialog that collects one piece of text: the log's description, or a filter regex.+ * A dialog that collects one piece of text: the filter regex.  *  * Replaces the hand-built `EditorDialog` (an `EditText` inside a `FrameLayout` inside an  * `AlertDialog`), which existed because there is no framework dialog for this. The 10,000-character
logviewer/src/main/res/values/strings.xml
diff --git a/logviewer/src/main/res/values/strings.xml b/logviewer/src/main/res/values/strings.xmlindex 8d2890ace3..c985d76566 100644--- a/logviewer/src/main/res/values/strings.xml+++ b/logviewer/src/main/res/values/strings.xml@@ -37,21 +37,11 @@     <!-- Bottom button when viewing one app's log: switches to the whole system log. -->     <string name="action_show_system_log">Show system log</string> -    <!-- Overflow item and dialog title: which logcat ring buffers to read. -->-    <string name="log_buffers">Log buffers</string>-    <!-- Top bar action and dialog title: the minimum severity of the lines shown. -->-    <string name="log_level">Log level</string>-     <!-- Top bar action and dialog title: filter the log with a regular expression. -->     <string name="set_filter">Set filter</string>     <!-- Hint inside the empty "Set filter" text field. -->     <string name="set_filter_editor_hint">Regex</string> -    <!-- Top bar action, when the log has no description yet. -->-    <string name="add_description">Add description</string>-    <!-- Top bar action, when the log already has a description. -->-    <string name="update_description">Update description</string>-     <!-- Shown instead of the device log when a secondary user or work profile asks for it. The          device log contains other users' activity, so only the primary user may read it. -->     <string name="error_system_log_secondary_user">The device log is only available to the primary user</string>
logviewer/src/screenshotTest/kotlin/com/vayunmathur/logviewer/ui/MetadataPreviews.kt
diff --git a/logviewer/src/screenshotTest/kotlin/com/vayunmathur/logviewer/ui/MetadataPreviews.kt b/logviewer/src/screenshotTest/kotlin/com/vayunmathur/logviewer/ui/MetadataPreviews.ktindex b7fd4f656b..5156196e9b 100644--- a/logviewer/src/screenshotTest/kotlin/com/vayunmathur/logviewer/ui/MetadataPreviews.kt+++ b/logviewer/src/screenshotTest/kotlin/com/vayunmathur/logviewer/ui/MetadataPreviews.kt@@ -23,7 +23,6 @@ private object PreviewActions : LogViewerActions {     override fun share() {}     override fun report() {}     override fun save(uri: Uri) {}-    override fun setDescription(description: String) {}     override fun zoom(factor: Float) {}     override fun setBuffers(buffers: List<String>) {}     override fun setLevel(level: LogLevel) {}@@ -77,7 +76,6 @@ class MetadataPreviews {                     lines = SAMPLE_LINES,                     kind = LogKind.ErrorReport,                     fontSizeSp = LogKind.ErrorReport.initialFontSizeSp,-                    canCopy = true,                     showReportButton = true,                     snapshotFileName = "weather-crash.txt",                 ),@@ -101,7 +99,6 @@ class MetadataPreviews {                     lines = SAMPLE_LINES,                     kind = LogKind.ErrorReport,                     fontSizeSp = LogKind.ErrorReport.initialFontSizeSp,-                    canCopy = true,                     showReportButton = true,                     snapshotFileName = "weather-crash.txt",                     stackTrace = SAMPLE_TRACE,@@ -129,7 +126,6 @@ class MetadataPreviews {                     ),                     kind = LogKind.Logcat,                     fontSizeSp = LogKind.Logcat.initialFontSizeSp,-                    canCopy = false,                     snapshotFileName = "weather-logcat.txt",                     logcat = LogcatFilters(                         buffers = listOf("main"),
logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentTest.kt
diff --git a/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentTest.kt b/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentTest.ktindex 71520aa646..0f38ecfc8a 100644--- a/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentTest.kt+++ b/logviewer/src/test/java/com/vayunmathur/logviewer/domain/LogDocumentTest.kt@@ -24,34 +24,30 @@ class LogDocumentTest {         // Every logcat dump ends in a newline. A blank final row would also mean "scroll to the         // last line" lands on an empty one.         val document = document("", "first\nsecond\n")-        assertEquals(listOf("first", "second"), document.bodyLines())+        assertEquals(listOf("first", "second"), document.bodyLines)     }      @Test     fun `blank lines inside the body are kept`() {         val document = document("", "first\n\nthird\n")-        assertEquals(listOf("first", "", "third"), document.bodyLines())+        assertEquals(listOf("first", "", "third"), document.bodyLines)     }      @Test     fun `an empty header produces no header rows`() {-        assertTrue(document("", "body\n").headerLines().isEmpty())+        assertTrue(document("", "body\n").headerLines.isEmpty())     }      @Test-    fun `display rows are header, blank, body, blank, description`() {+    fun `display rows are header, blank, body`() {         val document = document("type: logcat", "line\n")-        assertEquals(-            listOf("type: logcat", "", "line", "", "description: why"),-            document.displayLines("why"),-        )+        assertEquals(listOf("type: logcat", "", "line"), document.lines)+        assertEquals(listOf("line"), document("", "line\n").lines)     }      @Test-    fun `a small log is copyable and fenced`() {-        val document = document("type: logcat", "line\n")-        assertTrue(document.canCopy)-        val clip = document.clipText("")+    fun `a small log is fenced and not truncated`() {+        val clip = document("type: logcat", "line\n").clipText()         assertFalse(clip.truncated)         assertEquals("```\ntype: logcat\nline\n```\n", clip.text)     }@@ -60,7 +56,7 @@ class LogDocumentTest {     fun `an oversized log is truncated from the front and says so`() {         // Well past the 200 kB clipboard budget, so the head has to go.         val body = (1..20_000).joinToString("\n") { "line $it padded out to make it long enough" }-        val clip = document("type: logcat", body + "\n").clipText("")+        val clip = document("type: logcat", body + "\n").clipText()         assertTrue(clip.truncated)         assertTrue(clip.text.contains("[[TRUNCATED]]"))         // The tail is what explains a crash, so that is the end that survives.@@ -69,14 +65,16 @@ class LogDocumentTest {     }      @Test-    fun `a log too large to copy still reports so`() {-        val document = document("", "x".repeat(60_000))-        assertFalse(document.canCopy)+    fun `utf-8 width counts toward the clipboard budget`() {+        // 3 bytes per char: 70k chars is ~210 kB, over budget even though it is under 200k chars.+        val clip = document("", "\u4e00".repeat(70_000) + "\nlast\n").clipText()+        assertTrue(clip.truncated)+        assertTrue(clip.text.contains("last"))     }      @Test     fun `snapshot text is unfenced and untruncated`() {-        val text = document("type: logcat", "line\n").snapshotText("why")-        assertEquals("type: logcat\nline\n\ndescription: why\n", text)+        val text = StringBuilder().also { document("type: logcat", "line\n").writeSnapshot(it) }+        assertEquals("type: logcat\nline\n", text.toString())     } }
metadata_data/logviewer.md
diff --git a/metadata_data/logviewer.md b/metadata_data/logviewer.mdindex 71d5c0fc49..99505aec5b 100644--- a/metadata_data/logviewer.md+++ b/metadata_data/logviewer.md@@ -4,7 +4,7 @@ Features: - View the system log or a single app's log, with the newest lines first on screen - Filter by log level, by ring buffer, or with a regular expression - Read crash, ANR and battery reports sent by the system, including native tombstones-- Pinch to resize the text, and attach a description before sharing+- Pinch to resize the text - Copy to the clipboard, save to a file, or share without writing the log to storage - Jump straight from a crash report to the log of the app that crashed