Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(chat): show code blocks in a box with a copy button (#109)
Durganshu40a5ce753bc3
diff --git a/app/src/main/java/com/gotcha/ui/CodeBox.kt b/app/src/main/java/com/gotcha/ui/CodeBox.ktnew file mode 100644index 0000000..527eedb--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/CodeBox.kt@@ -0,0 +1,100 @@+package com.gotcha.ui++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import android.widget.Toast+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.ContentCopy+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.gotcha.ui.theme.GotchaMono+import com.gotcha.ui.theme.LocalSkin+import com.halilibo.richtext.markdown.Markdown+import com.halilibo.richtext.ui.material3.Material3RichText++/**+ * Markdown with its fenced code blocks drawn as [CodeBox]es, so a command the+ * user has to run can be copied exactly (issue #109).+ */+@Composable+fun RichMarkdown(markdown: String, modifier: Modifier = Modifier) {+ Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {+ splitFencedBlocks(markdown).forEach { segment ->+ when (segment) {+ is MarkdownSegment.Prose -> Material3RichText { Markdown(segment.markdown) }+ is MarkdownSegment.Code -> CodeBox(code = segment.code, language = segment.language)+ }+ }+ }+}++/**+ * A code block with a copy button: monospace, never wrapped mid-token (long+ * lines scroll sideways), and set apart from the prose around it.+ */+@Composable+fun CodeBox(code: String, language: String?, modifier: Modifier = Modifier) {+ val context = LocalContext.current+ val colors = MaterialTheme.colorScheme+ Surface(+ modifier = modifier.fillMaxWidth(),+ shape = RoundedCornerShape(LocalSkin.current.cornerSmall),+ color = colors.surfaceContainerHighest,+ contentColor = colors.onSurface+ ) {+ Column {+ Row(+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = language.orEmpty(),+ style = MaterialTheme.typography.labelMedium,+ color = colors.onSurfaceVariant,+ modifier = Modifier.weight(1f)+ )+ TextButton(onClick = { copyCode(context, code) }) {+ Icon(+ Icons.Rounded.ContentCopy,+ contentDescription = null,+ modifier = Modifier.size(16.dp)+ )+ Text("Copy", modifier = Modifier.padding(start = 6.dp))+ }+ }+ Text(+ text = code,+ fontFamily = GotchaMono,+ style = MaterialTheme.typography.bodyMedium,+ softWrap = false,+ modifier = Modifier+ .horizontalScroll(rememberScrollState())+ .padding(start = 12.dp, end = 12.dp, bottom = 12.dp)+ )+ }+ }+}++private fun copyCode(context: Context, code: String) {+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ cm.setPrimaryClip(ClipData.newPlainText("Code", code))+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()+}diff --git a/app/src/main/java/com/gotcha/ui/MarkdownSegment.kt b/app/src/main/java/com/gotcha/ui/MarkdownSegment.ktnew file mode 100644index 0000000..a73cc79--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/MarkdownSegment.kt@@ -0,0 +1,67 @@+package com.gotcha.ui++/**+ * A piece of a Markdown message: prose for the Markdown renderer, or a fenced+ * code block drawn as a [CodeBox] with its own copy button (issue #109).+ */+sealed interface MarkdownSegment {+ data class Prose(val markdown: String) : MarkdownSegment+ data class Code(val code: String, val language: String?) : MarkdownSegment+}++private val OPENING_FENCE = Regex("^( {0,3})(`{3,}|~{3,})\\s*([^\\s`]*)[^`]*$")++/**+ * Splits [markdown] at its top-level fenced code blocks. The renderer draws+ * those itself with no way to add a copy button, so they are taken out and+ * drawn by [CodeBox] instead; everything else stays Markdown.+ *+ * Follows CommonMark's fence rules: up to three spaces of indent, three or more+ * backticks or tildes, closed by a fence of the same character at least as+ * long. An unclosed fence runs to the end of the text, which is also how a+ * reply still being streamed looks. Fences nested deeper (in a list item or a+ * quote) are left to the renderer.+ */+fun splitFencedBlocks(markdown: String): List<MarkdownSegment> {+ val segments = mutableListOf<MarkdownSegment>()+ val prose = StringBuilder()+ val lines = markdown.lines()+ var i = 0+ while (i < lines.size) {+ val open = OPENING_FENCE.matchEntire(lines[i])+ if (open == null) {+ prose.appendLine(lines[i])+ i+++ continue+ }+ val indent = open.groupValues[1].length+ val fence = open.groupValues[2]+ val closing = Regex("^ {0,3}[${fence[0]}]{${fence.length},}\\s*$")+ val body = mutableListOf<String>()+ i+++ while (i < lines.size && !closing.matches(lines[i])) {+ body += lines[i].removeIndent(indent)+ i+++ }+ i++ // The closing fence, or past the end.+ prose.flushInto(segments)+ segments += MarkdownSegment.Code(+ code = body.joinToString("\n").trimEnd(),+ language = open.groupValues[3].ifBlank { null }+ )+ }+ prose.flushInto(segments)+ return segments+}++private fun StringBuilder.flushInto(segments: MutableList<MarkdownSegment>) {+ val text = toString().trim('\n')+ if (text.isNotBlank()) segments += MarkdownSegment.Prose(text)+ setLength(0)+}++/** Drops up to [indent] leading spaces, as CommonMark does for an indented fence's body. */+private fun String.removeIndent(indent: Int): String {+ val spaces = takeWhile { it == ' ' }.length.coerceAtMost(indent)+ return substring(spaces)+}diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.ktindex adbcd36..a656eca 100644--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt@@ -58,8 +58,6 @@ import com.gotcha.agent.UiMessageimport com.gotcha.ui.theme.GotchaMonoimport com.gotcha.ui.theme.LocalSkinimport com.gotcha.ui.theme.SkinDropdownMenu-import com.halilibo.richtext.markdown.Markdown-import com.halilibo.richtext.ui.material3.Material3RichText@OptIn(ExperimentalFoundationApi::class)@Composable@@ -230,9 +228,7 @@ fun MessageBubble(expanded = expanded)} else {- Material3RichText {- Markdown(displayText)- }+ RichMarkdown(displayText)}}if (isAssistant && message.text.isNotEmpty()) {@@ -474,9 +470,7 @@ private fun SubAgentContent(// Final answer with markdown renderingif (answer.isNotBlank()) {- Material3RichText {- Markdown(answer)- }+ RichMarkdown(answer)}}}diff --git a/app/src/test/java/com/gotcha/ui/MarkdownSegmentTest.kt b/app/src/test/java/com/gotcha/ui/MarkdownSegmentTest.ktnew file mode 100644index 0000000..cdc85c2--- /dev/null+++ b/app/src/test/java/com/gotcha/ui/MarkdownSegmentTest.kt@@ -0,0 +1,95 @@+package com.gotcha.ui++import com.gotcha.ui.MarkdownSegment.Code+import com.gotcha.ui.MarkdownSegment.Prose+import org.junit.Assert.assertEquals+import org.junit.Test++/** [splitFencedBlocks] decides which parts of a reply get a copyable code box (issue #109). */+class MarkdownSegmentTest {++ @Test+ fun `text without fences stays one prose segment`() {+ val md = "Run `ls` to list files.\n\n1. One\n2. Two"+ assertEquals(listOf(Prose(md)), splitFencedBlocks(md))+ }++ @Test+ fun `a fenced block is split out with its language`() {+ val md = """+ In Termux, run:++ ```bash+ echo "allow-external-apps=true" >> ~/.termux/termux.properties+ ```++ then restart Termux.+ """.trimIndent()+ assertEquals(+ listOf(+ Prose("In Termux, run:"),+ Code("echo \"allow-external-apps=true\" >> ~/.termux/termux.properties", "bash"),+ Prose("then restart Termux.")+ ),+ splitFencedBlocks(md)+ )+ }++ @Test+ fun `a fence without a language has none`() {+ assertEquals(listOf(Code("pkg update", null)), splitFencedBlocks("```\npkg update\n```"))+ }++ @Test+ fun `tilde fences and longer fences are recognized`() {+ assertEquals(listOf(Code("a\nb", "sh")), splitFencedBlocks("~~~sh\na\nb\n~~~"))+ // A shorter fence inside does not close a longer one.+ assertEquals(+ listOf(Code("```\ninner\n```", "md")),+ splitFencedBlocks("````md\n```\ninner\n```\n````")+ )+ }++ @Test+ fun `backticks do not close a tilde fence`() {+ assertEquals(listOf(Code("x\n```", null)), splitFencedBlocks("~~~\nx\n```\n~~~"))+ }++ @Test+ fun `an unclosed fence runs to the end`() {+ assertEquals(+ listOf(Prose("Streaming:"), Code("line 1\nline 2", "bash")),+ splitFencedBlocks("Streaming:\n```bash\nline 1\nline 2")+ )+ }++ @Test+ fun `an indented fence drops the same indent from its body`() {+ assertEquals(listOf(Code("cd ~\n ls", null)), splitFencedBlocks(" ```\n cd ~\n ls\n ```"))+ }++ @Test+ fun `a fence indented four spaces is left to the renderer`() {+ val md = " ```\n code\n ```"+ assertEquals(listOf(Prose(md)), splitFencedBlocks(md))+ }++ @Test+ fun `inline triple backticks are not a fence`() {+ val md = "Use ```code``` inline."+ assertEquals(listOf(Prose(md)), splitFencedBlocks(md))+ }++ @Test+ fun `consecutive blocks keep their order and blank code is kept`() {+ assertEquals(+ listOf(Code("a", "bash"), Code("", null), Prose("end")),+ splitFencedBlocks("```bash\na\n```\n```\n```\nend")+ )+ }++ @Test+ fun `empty text has no segments`() {+ assertEquals(emptyList<MarkdownSegment>(), splitFencedBlocks(""))+ }+}