securemail: remove plain-text markup parser (opened messages slowly)
- Commit
b7000176ed451b81d820a2a331b8f6469ef87bc3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-02 06:48 UTC (1 month ago)
- Parents
e4aa0a8
Removes 426f2162d. Opening a message became slow (about 5 s for some) after it landed: PlainTextMarkup.parse ran a large multi-alternative regex (with lookbehinds) over the whole body on the UI thread while the reader was being composed. Messages stored before the MIME fix still hold their full raw MIME as the body, so it ran over kilobytes of base64. MessageBodyView's plain-text path is back to exactly its pre-426f2162d state (bare URL / email linkify only); PlainTextMarkup and its test are deleted. HTML mail still renders through HtmlText. Verified: :securemail:compileDevKotlin, unit tests, lint clean.
Diff
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.ktdeleted file mode 100644index 078b67d0e1..0000000000--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkup.kt+++ /dev/null@@ -1,98 +0,0 @@-package com.vayunmathur.securemail.domain.mail--/**- * Light markup for plain-text mail bodies. Proton (and other clients that- * derive text/plain from rich text) write links as `[text](url)`, bold as- * `**x**`, italics as `*x*`/`_x_`, bullets as `* item`, headings as `# x`.- * This turns those into styled runs without reflowing anything: line breaks- * are kept exactly as sent, and only http(s)/mailto targets become links.- * Bare URLs and email addresses are linked too.- */-object PlainTextMarkup {-- /** One styled stretch of text; [url] set when it should be tappable. */- data class Run(- val text: String,- val url: String? = null,- val bold: Boolean = false,- val italic: Boolean = false,- )-- fun parse(text: String): List<Run> {- val runs = mutableListOf<Run>()- text.split("\n").forEachIndexed { index, rawLine ->- if (index > 0) runs += Run("\n")- val heading = HEADING.matchEntire(rawLine)- val bullet = BULLET.matchEntire(rawLine)- when {- heading != null -> inline(heading.groupValues[1], runs, bold = true)- bullet != null -> {- runs += Run(bullet.groupValues[1] + "\u2022 ")- inline(bullet.groupValues[2], runs, bold = false)- }- else -> inline(rawLine, runs, bold = false)- }- }- return merge(runs)- }-- private fun inline(line: String, out: MutableList<Run>, bold: Boolean) {- var pos = 0- for (m in TOKEN.findAll(line)) {- if (m.range.first > pos) out += Run(line.substring(pos, m.range.first), bold = bold)- val g = m.groupValues- when {- m.value.startsWith("![") -> out += linkOrRaw(g[1].ifBlank { "image" }, g[2], m.value, bold)- g[3].isNotEmpty() -> out += linkOrRaw(g[3], g[4], m.value, bold)- g[5].isNotEmpty() -> out += Run(g[5].removePrefix("mailto:"), g[5], bold = bold)- g[6].isNotEmpty() || g[7].isNotEmpty() -> out += Run(g[6] + g[7], bold = true)- g[8].isNotEmpty() || g[9].isNotEmpty() -> out += Run(g[8] + g[9], bold = bold, italic = true)- g[10].isNotEmpty() -> {- val url = g[10].trimEnd('.', ',', ';', ':', '!', '?', ')', ']', '\'', '"')- out += Run(url, url, bold = bold)- if (url.length < g[10].length) out += Run(g[10].substring(url.length), bold = bold)- }- g[11].isNotEmpty() -> out += Run(g[11], "mailto:${g[11]}", bold = bold)- }- pos = m.range.last + 1- }- if (pos < line.length) out += Run(line.substring(pos), bold = bold)- }-- /** A markdown link only becomes tappable for safe schemes; anything else stays literal. */- private fun linkOrRaw(label: String, target: String, raw: String, bold: Boolean): Run =- if (SAFE_SCHEME.containsMatchIn(target)) Run(label, target, bold = bold) else Run(raw, bold = bold)-- /** Joins adjacent runs with identical styling so the UI builds fewer spans. */- private fun merge(runs: List<Run>): List<Run> {- val out = mutableListOf<Run>()- for (r in runs) {- if (r.text.isEmpty()) continue- val last = out.lastOrNull()- if (last != null && last.joinsWith(r)) {- out[out.lastIndex] = last.copy(text = last.text + r.text)- } else {- out += r- }- }- return out- }-- /** Two plain (non-link) runs with the same weight and slant render identically. */- private fun Run.joinsWith(next: Run): Boolean =- url == null && next.url == null && bold == next.bold && italic == next.italic-- private val HEADING = Regex("""^#{1,6}\s+(.+?)\s*#*\s*$""")- private val BULLET = Regex("""^(\s*)[*+-]\s+(.*)$""")- private val SAFE_SCHEME = Regex("""^(https?://|mailto:)""", RegexOption.IGNORE_CASE)- private val TOKEN = Regex(- """!\[([^\]\n]*)]\(([^)\s]+)\)""" + // 1,2 image: shown as a link, never loaded- """|\[([^\]\n]+)]\(([^)\s]+)\)""" + // 3,4 link- """|<((?:https?://|mailto:)[^>\s]+)>""" + // 5 autolink- """|\*\*([^*\n]+)\*\*|__([^_\n]+)__""" + // 6,7 bold- """|(?<![\w*])\*([^*\s](?:[^*\n]*[^*\s])?)\*(?![\w*])""" + // 8 italic- """|(?<![\w_])_([^_\s](?:[^_\n]*[^_\s])?)_(?![\w_])""" + // 9 italic- """|(https?://[^\s<>"]+)""" + // 10 bare URL- """|([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})""", // 11 email address- )-}
securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.ktindex f10d07226e..8c4b59d4da 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt@@ -17,8 +17,6 @@ import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.buildAnnotatedString-import androidx.compose.ui.text.font.FontStyle-import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.HtmlText@@ -26,7 +24,6 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.securemail.data.StoredMessage-import com.vayunmathur.securemail.domain.mail.PlainTextMarkup /** * Message body: the sender's HTML part when there is one (links, lists,@@ -84,7 +81,7 @@ private fun PlainBody(msg: StoredMessage) { val (main, quoted) = remember(body) { splitQuotedText(body) } val linkColor = MaterialTheme.colorScheme.primary val shown = if (showQuotes || quoted.isEmpty()) body else main- val annotated = remember(shown, linkColor) { styled(shown, linkColor) }+ val annotated = remember(shown, linkColor) { linkify(shown, linkColor) } Text( annotated, style = MaterialTheme.typography.bodyMedium,@@ -97,23 +94,14 @@ private fun PlainBody(msg: StoredMessage) { } } -/** Plain text with light markup ([text](url), **bold**, bullets...) applied; see [PlainTextMarkup]. */-private fun styled(text: String, linkColor: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString {- val linkStyle = TextLinkStyles(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline))- for (run in PlainTextMarkup.parse(text)) {- val start = length- append(run.text)- if (run.bold || run.italic) {- addStyle(- SpanStyle(- fontWeight = if (run.bold) FontWeight.Bold else null,- fontStyle = if (run.italic) FontStyle.Italic else null,- ),- start,- length,- )- }- run.url?.let { addLink(LinkAnnotation.Url(it, linkStyle), start, length) }+/** Plain text with http(s) URLs and email addresses turned into tappable links. */+private fun linkify(text: String, color: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString {+ append(text)+ val style = TextLinkStyles(SpanStyle(color = color, textDecoration = TextDecoration.Underline))+ URL.findAll(text).forEach { m ->+ val raw = m.value.trimEnd('.', ',', ')', ']', ';', ':', '!', '?')+ val target = if (raw.contains('@') && !raw.startsWith("http", ignoreCase = true)) "mailto:$raw" else raw+ addLink(LinkAnnotation.Url(target, style), m.range.first, m.range.first + raw.length) } } @@ -130,5 +118,6 @@ private fun splitQuotedText(body: String): Pair<String, String> { return body to "" } +private val URL = Regex("""https?://[^\s<>"]+|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}""") private val REMOTE_REF = Regex("""(?i)(src|background|srcset)\s*=\s*["']?\s*https?://|url\(\s*["']?https?://""") private val QUOTE_MARKERS = listOf("protonmail_quote", "gmail_quote", "yahoo_quoted", "moz-cite-prefix", "<blockquote")
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.ktdeleted file mode 100644index 4aa7f382c4..0000000000--- a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/PlainTextMarkupTest.kt+++ /dev/null@@ -1,58 +0,0 @@-package com.vayunmathur.securemail.domain.mail--import com.vayunmathur.securemail.domain.mail.PlainTextMarkup.Run-import kotlin.test.Test-import kotlin.test.assertEquals--class PlainTextMarkupTest {-- @Test- fun protonStyleLink() {- assertEquals(- listOf(Run("See "), Run("the docs", "https://proton.me/support"), Run(" please")),- PlainTextMarkup.parse("See [the docs](https://proton.me/support) please"),- )- }-- @Test- fun unsafeSchemeStaysLiteral() {- assertEquals(- listOf(Run("[click](javascript:alert(1))")),- PlainTextMarkup.parse("[click](javascript:alert(1))"),- )- }-- @Test- fun boldItalicAndHeading() {- assertEquals(- listOf(Run("Title", bold = true), Run("\nis "), Run("big", bold = true), Run(" and "), Run("slanted", italic = true)),- PlainTextMarkup.parse("# Title\nis **big** and *slanted*"),- )- }-- @Test- fun bulletsAndLineBreaksPreserved() {- assertEquals(- listOf(Run("Items:\n\u2022 one\n \u2022 two\n\nbye")),- PlainTextMarkup.parse("Items:\n* one\n - two\n\nbye"),- )- }-- @Test- fun bareUrlTrailingPunctuationAndEmail() {- assertEquals(- listOf(- Run("Go to "),- Run("https://maemail.org/x", "https://maemail.org/x"),- Run(". Mail "),- Run("[email protected]", "mailto:[email protected]"),- ),- PlainTextMarkup.parse("Go to https://maemail.org/x. Mail [email protected]"),- )- }-- @Test- fun snakeCaseAndMathAreNotItalic() {- assertEquals(listOf(Run("my_var_name and 2*3*4")), PlainTextMarkup.parse("my_var_name and 2*3*4"))- }-}