Modern Apps git

← Modern-Apps.git

email: add a load-remote-images setting

Commit
a3fb4d23dfd6bb9aa21f3eccdec96bb51bae269a
Author
Vayun Mathur <[email protected]>
When
2026-08-05 19:27 UTC (4 months ago)
Parents
c1fb44e

Diff

email/src/main/java/com/vayunmathur/email/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/EmailModels.ktindex 7f81295855..79cabe1056 100644--- a/email/src/main/java/com/vayunmathur/email/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailModels.kt@@ -170,9 +170,67 @@ fun accountColor(email: String): Long {     return ACCOUNT_COLORS[(hash and Int.MAX_VALUE) % ACCOUNT_COLORS.size] } -/** Plain-text rendering of this message's body (strips HTML when [isHtml]). */-fun EmailMessage.plainTextBody(): String? =-    body?.let { if (isHtml) HtmlCompat.fromHtml(it, HtmlCompat.FROM_HTML_MODE_LEGACY).toString() else it }+/**+ * Content of `<script>`, `<style>`, `<head>` and `<title>` elements.+ *+ * [HtmlCompat.fromHtml] emits the *text* inside these rather than dropping+ * them, so a message whose body is a full HTML document renders its stylesheet+ * as the first hundred characters of the preview.+ */+private val HTML_NON_CONTENT = Regex("""<(script|style|head|title)\b[^>]*>.*?</\1\s*>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))+private val HTML_COMMENT = Regex("""<!--.*?-->""", RegexOption.DOT_MATCHES_ALL)+private val HTML_DECLARATION = Regex("""<[!?][^>]*>""")+/** Tags common enough that their presence means the body is HTML whatever the flag says. */+private val LOOKS_LIKE_HTML = Regex("""<(html|body|head|div|table|p|br|span|a|img|font)\b[^>]*>""", RegexOption.IGNORE_CASE)+/**+ * Includes the non-breaking space `fromHtml` produces from `&nbsp;` and the+ * Unicode line/paragraph separators, none of which `\s` matches.+ */+private val WHITESPACE_RUN = Regex("""[\s\u00A0\u2028\u2029]+""")++/**+ * Characters that draw as an empty box, or as nothing at all.+ *+ * `fromHtml` returns a `Spanned` in which every `<img>` is a U+FFFC anchored to+ * an `ImageSpan`; `toString()` discards the span and leaves the placeholder+ * behind with nothing to stand for. U+FFFD is the decoder's marker for bytes it+ * could not make sense of. The zero-width characters are the invisible padding+ * marketing mail uses to pull its preheader around, and the C0/C1 controls come+ * through from mail that was never really text.+ *+ * Deliberately excludes tab, newline and the vertical whitespace controls -+ * those separate words, so deleting them would run the words together where+ * collapsing them to a space does not.+ */+private val UNRENDERABLE = Regex("[\\uFFFC\\uFFFD\\u200B-\\u200F\\uFEFF\\u0000-\\u0008\\u000E-\\u001F\\u007F]")++/**+ * Plain-text rendering of this message's body.+ *+ * Falls back to sniffing the markup when [EmailMessage.isHtml] is false, because+ * plenty of senders set `text/plain` on a body that is anything but.+ */+fun EmailMessage.plainTextBody(): String? {+    val raw = body ?: return null+    if (!isHtml && !LOOKS_LIKE_HTML.containsMatchIn(raw)) return raw.replace(UNRENDERABLE, "")+    val stripped = raw+        .replace(HTML_COMMENT, " ")+        .replace(HTML_NON_CONTENT, " ")+        .replace(HTML_DECLARATION, " ")+    return HtmlCompat.fromHtml(stripped, HtmlCompat.FROM_HTML_MODE_LEGACY)+        .toString()+        .replace(UNRENDERABLE, "")+}++/**+ * A single-line snippet of the body for list rows, widgets and notifications.+ *+ * Collapses whitespace before truncating: the block structure of an HTML mail+ * turns into leading blank lines, so [plainTextBody] truncated as-is is often+ * entirely empty.+ */+fun EmailMessage.previewText(maxChars: Int): String =+    (plainTextBody() ?: "").replace(WHITESPACE_RUN, " ").trim().take(maxChars)  /** Display name for a "Name <addr>" sender header, falling back to the address.  * Implemented via own RFC2047 decode + simple parse to remove Jakarta dependency. */
email/src/main/java/com/vayunmathur/email/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/EmailViewModel.ktindex 01143a90d7..6c37ff735e 100644--- a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt@@ -221,7 +221,7 @@ class EmailViewModel(application: Application) :         _aiSummary.value = null          val emailSnippets = messages.take(5).joinToString("\n---\n") { msg ->-            val plainBody = msg.plainTextBody()?.take(150) ?: ""+            val plainBody = msg.previewText(150)             "Subject: ${msg.subject}\nFrom: ${senderDisplayName(msg.from)}\n$plainBody"         }         val prompt = "Summarize these emails in 1-2 sentences:\n\n$emailSnippets"
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex 8b0926c66f..9bd15e5f89 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -809,7 +809,7 @@ fun MessageListScreen(                                             text = senderDisplayName(message.from),                                             style = MaterialTheme.typography.titleSmall                                         )-                                        val preview = remember(message.body, message.isHtml) { (message.plainTextBody() ?: "").take(100) }+                                        val preview = remember(message.body, message.isHtml) { message.previewText(100) }                                         Text(                                             text = preview,                                             style = MaterialTheme.typography.bodySmall,@@ -1062,7 +1062,9 @@ fun MessageItem(         }          if (msg.isHtml && msg.body != null) {-            var loadImages by remember(msg.id) { mutableStateOf(false) }+            val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }+            val loadRemoteByDefault by settings.loadRemoteImages.collectAsStateWithLifecycle()+            var loadImages by remember(msg.id, loadRemoteByDefault) { mutableStateOf(loadRemoteByDefault) }             var showQuotes by remember(msg.id) { mutableStateOf(false) }             var cidMap by remember(msg.id) { mutableStateOf<Map<String, java.io.File>>(emptyMap()) }             val bodyHasCid = remember(msg.body) { msg.body.contains("cid:", ignoreCase = true) }@@ -2027,6 +2029,17 @@ fun SettingsScreen(viewModel: EmailViewModel, onBack: () -> Unit) {                 .verticalScroll(rememberScrollState()),             verticalArrangement = Arrangement.spacedBy(16.dp),         ) {+            val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }+            val loadRemoteImages by settings.loadRemoteImages.collectAsStateWithLifecycle()+            Text(stringResource(R.string.reading), style = MaterialTheme.typography.titleMedium)+            com.vayunmathur.library.ui.SettingsSwitchRow(+                title = stringResource(R.string.load_remote_images),+                supportingText = stringResource(R.string.load_remote_images_summary),+                checked = loadRemoteImages,+                onCheckedChange = { settings.setLoadRemoteImages(it) },+            )+            HorizontalDivider()+             Text(stringResource(R.string.signatures), style = MaterialTheme.typography.titleMedium)             if (accounts.isEmpty()) {                 Text(stringResource(R.string.select_account))
email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSettings.ktnew file mode 100644index 0000000000..4081c595f3--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt@@ -0,0 +1,54 @@+package com.vayunmathur.email.data++import android.content.Context+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * App-wide preferences that belong to no particular account.+ *+ * Account settings live on the account row in Room, and the various workers+ * keep their own bookkeeping in private [android.content.SharedPreferences]+ * files. This is the third thing: a handful of user-facing choices that apply+ * to every account, read from composables that have a [Context] and nothing+ * else.+ *+ * A single instance per process so every reader observes the same+ * [StateFlow] - two instances would each hold their own copy of the value and+ * only one of them would update when the switch is flipped.+ */+class EmailSettings private constructor(context: Context) {++    private val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    private val _loadRemoteImages = MutableStateFlow(prefs.getBoolean(KEY_LOAD_REMOTE_IMAGES, false))++    /**+     * Whether to fetch remote images without asking.+     *+     * Off by default: a remote image in a mail is a read receipt for the+     * sender, so turning them on is a choice the user has to make rather than+     * one made for them. When on, the "Remote images blocked" bar never+     * appears and messages render complete on open.+     */+    val loadRemoteImages: StateFlow<Boolean> = _loadRemoteImages.asStateFlow()++    fun setLoadRemoteImages(enabled: Boolean) {+        prefs.edit().putBoolean(KEY_LOAD_REMOTE_IMAGES, enabled).apply()+        _loadRemoteImages.value = enabled+    }++    companion object {+        private const val PREFS = "email_settings"+        private const val KEY_LOAD_REMOTE_IMAGES = "load_remote_images"++        @Volatile+        private var instance: EmailSettings? = null++        fun get(context: Context): EmailSettings =+            instance ?: synchronized(this) {+                instance ?: EmailSettings(context).also { instance = it }+            }+    }+}
email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.ktindex e35b12cd9b..635f8cddcc 100644--- a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt@@ -27,6 +27,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.content.FileProvider+import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.core.net.toUri import com.vayunmathur.email.accountColor import com.vayunmathur.email.senderDisplayName@@ -147,7 +148,9 @@ fun EmlViewerScreen(                     Spacer(Modifier.height(12.dp))                      if (msg.isHtml && msg.body != null) {-                        var loadImages by remember(uriString) { mutableStateOf(false) }+                        val settings = remember(context) { com.vayunmathur.email.data.EmailSettings.get(context) }+                        val loadRemoteByDefault by settings.loadRemoteImages.collectAsStateWithLifecycle()+                        var loadImages by remember(uriString, loadRemoteByDefault) { mutableStateOf(loadRemoteByDefault) }                         if (!loadImages && cidMap.isEmpty()) {                             Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {                                 Text(stringResource(R.string.remote_images_blocked), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt
diff --git a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.ktindex 69c14fbc0a..9a880c5a0b 100644--- a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt+++ b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt@@ -25,7 +25,7 @@ import androidx.glance.unit.ColorProvider import com.vayunmathur.email.MainActivity import com.vayunmathur.email.EmailMessage import com.vayunmathur.email.accountColor-import com.vayunmathur.email.plainTextBody+import com.vayunmathur.email.previewText import com.vayunmathur.email.senderDisplayName import com.vayunmathur.email.data.EmailDatabase import com.vayunmathur.library.widgets.DynamicThemeGlance@@ -193,7 +193,7 @@ class EmailWidget : GlanceAppWidget() {                     maxLines = 1                 )                 Text(-                    text = (msg.plainTextBody() ?: "").take(50),+                    text = msg.previewText(50),                     style = TextStyle(                         fontSize = 12.sp,                         color = GlanceTheme.colors.onSurfaceVariant
email/src/main/res/values/strings.xml
diff --git a/email/src/main/res/values/strings.xml b/email/src/main/res/values/strings.xmlindex 9a9b56879c..7431eca903 100644--- a/email/src/main/res/values/strings.xml+++ b/email/src/main/res/values/strings.xml@@ -78,6 +78,9 @@     <string name="unsubscribing">Unsubscribing…</string>     <string name="accounts">Accounts</string>     <string name="remote_images_blocked">Remote images blocked</string>+    <string name="reading">Reading</string>+    <string name="load_remote_images">Load remote images</string>+    <string name="load_remote_images_summary">Show images hosted on the web without asking. Senders can use these to tell when you opened a message.</string>     <string name="cc_bcc">Cc/Bcc</string>     <string name="blocked_senders">Blocked senders</string>     <string name="inline_images">Inline images (<xliff:g id="count" example="2">%1$s</xliff:g> - <xliff:g id="size" example="1.2 MB">%2$s</xliff:g>)</string>
library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.ktindex 53415d16b5..404cd903e9 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt@@ -1,5 +1,6 @@ package com.vayunmathur.library.ui +import android.content.Intent import android.view.ViewGroup import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse@@ -14,6 +15,16 @@ import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.viewinterop.AndroidView import java.io.File +/**+ * Renders an HTML fragment (an email body, typically) in an inline, wrap-content+ * [WebView].+ *+ * @param openLinksExternally hands tapped links to the system browser rather than+ *   letting them navigate inside this view. The view is sized to its content and+ *   embedded in a scrolling column, so in-place navigation would strand the user+ *   on a full web page inside a message. Only turn this off for content that is+ *   genuinely meant to be browsed in place.+ */ @Composable fun HtmlText(     html: String,@@ -21,6 +32,7 @@ fun HtmlText(     blockRemoteImages: Boolean = true,     hideQuotes: Boolean = false,     cidMap: Map<String, File> = emptyMap(),+    openLinksExternally: Boolean = true, ) {     val backgroundColor = MaterialTheme.colorScheme.surface     val onSurfaceColor = MaterialTheme.colorScheme.onSurface@@ -42,7 +54,12 @@ fun HtmlText(             h         }     }-    val cidMapState = remember(cidMap) { cidMap }+    // One client instance for the life of the view, mutated in place. Swapping in a+    // new WebViewClient on every recomposition used to be how the cid map was+    // refreshed, and the guard that did it could never fire.+    val webClient = remember { HtmlTextWebViewClient() }+    webClient.cidMap = cidMap+    webClient.openLinksExternally = openLinksExternally      AndroidView(         modifier = modifier,@@ -61,58 +78,11 @@ fun HtmlText(                 settings.blockNetworkImage = blockRemoteImages                 setBackgroundColor(backgroundColor.toArgb()) -                webViewClient = object : WebViewClient() {-                    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {-                        val url = request?.url?.toString() ?: return null-                        // Intercept our synthetic cid:// host-                        if (url.contains("cid.local")) {-                            val cid = request.url?.lastPathSegment-                                ?: request.url?.path?.removePrefix("/")?.substringAfterLast("/")-                                ?: return null-                            // CID may be url-encoded-                            val decodedCid = try { java.net.URLDecoder.decode(cid, "UTF-8") } catch (_: Exception) { cid }-                            // Try exact match, then stripped angle brackets variant-                            val file = cidMapState[decodedCid]-                                ?: cidMapState[decodedCid.removePrefix("<").removeSuffix(">")]-                                ?: cidMapState.entries.firstOrNull { it.key.equals(decodedCid, ignoreCase = true) }?.value-                                ?: return null-                            if (!file.exists()) return null-                            val mime = guessMimeType(file)-                            return try {-                                WebResourceResponse(mime, "utf-8", file.inputStream())-                            } catch (_: Exception) { null }-                        }-                        // Block remote if requested but allow cid interception already handled-                        return null-                    }-                }+                webViewClient = webClient             }         },         update = { webView ->             webView.settings.blockNetworkImage = blockRemoteImages-            // Update client map when cidMap changes-            if (cidMapState !== cidMap) {-                // State already captured via remember; re-create client to capture new map-                webView.webViewClient = object : WebViewClient() {-                    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {-                        val url = request?.url?.toString() ?: return null-                        if (url.contains("cid.local")) {-                            val cid = request.url?.lastPathSegment ?: return null-                            val decodedCid = try { java.net.URLDecoder.decode(cid, "UTF-8") } catch (_: Exception) { cid }-                            val file = cidMap[decodedCid]-                                ?: cidMap[decodedCid.removePrefix("<").removeSuffix(">")]-                                ?: cidMap.entries.firstOrNull { it.key.equals(decodedCid, ignoreCase = true) }?.value-                                ?: return null-                            if (!file.exists()) return null-                            val mime = guessMimeType(file)-                            return try {-                                WebResourceResponse(mime, null, file.inputStream())-                            } catch (_: Exception) { null }-                        }-                        return null-                    }-                }-            }             val htmlToLoad = if (cidMap.isEmpty()) html else rewrittenHtml             val richCss = """                 h1,h2,h3 { margin:0.5em 0; font-weight:600; line-height:1.25; }@@ -197,6 +167,67 @@ fun HtmlText(     ) } +/**+ * Serves `cid:` inline attachments from local files and keeps navigation out of+ * the view.+ *+ * Both fields are `var` because the composable owns a single instance for the+ * life of the [WebView] and updates it in place; replacing the client on+ * recomposition resets state the WebView keeps per-client.+ */+private class HtmlTextWebViewClient : WebViewClient() {++    var cidMap: Map<String, File> = emptyMap()+    var openLinksExternally: Boolean = true++    override fun shouldInterceptRequest(+        view: WebView?,+        request: WebResourceRequest?,+    ): WebResourceResponse? {+        val uri = request?.url ?: return null+        if (uri.host != CID_HOST) return null++        val cid = uri.lastPathSegment+            ?: uri.path?.removePrefix("/")?.substringAfterLast("/")+            ?: return null+        // A Content-ID can legitimately contain characters the URL had to encode.+        val decoded = try { java.net.URLDecoder.decode(cid, "UTF-8") } catch (_: Exception) { cid }+        val file = cidMap[decoded]+            ?: cidMap[decoded.removePrefix("<").removeSuffix(">")]+            ?: cidMap.entries.firstOrNull { it.key.equals(decoded, ignoreCase = true) }?.value+            ?: return null+        if (!file.exists()) return null++        return try {+            WebResourceResponse(guessMimeType(file), "utf-8", file.inputStream())+        } catch (_: Exception) {+            null+        }+    }++    override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {+        if (!openLinksExternally) return false+        val uri = request?.url ?: return false+        // Our own inline-image host, and the synthetic document itself, are not links.+        if (uri.host == CID_HOST && uri.path.isNullOrEmpty()) return false+        if (uri.scheme?.lowercase() in IN_PLACE_SCHEMES) return false+        val context = view?.context ?: return false++        ExternalIntents.launch(+            context,+            Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+        )+        // Consumed either way: this view is sized to its content, so falling back to+        // in-place navigation when no app handles the link is worse than doing nothing.+        return true+    }++    private companion object {+        const val CID_HOST = "cid.local"+        val IN_PLACE_SCHEMES = setOf("data", "about", "javascript", "blob")+    }+}+ private fun guessMimeType(file: File): String {     val name = file.name.lowercase()     return when {