Modern Apps git

← Modern-Apps.git

perf: decode document images off the main thread, sampled

Commit
13ad1679febafcc9b94ae54a599865f960f9aea8
Author
Vayun Mathur <[email protected]>
When
2026-11-20 19:04 UTC (15 days ago)
Parents
7bb7ea5
Office decoded embedded document images full-size inside
remember{} on the composition thread (OdfImageView, and the
full-screen image viewer), and pdf readAsJpeg decoded stamp
photos at native resolution on the caller's thread - a 20MP
photo committed ~80MB before JPEG re-encode.

Decodes now run via produceState/withContext(Dispatchers.IO)
with a bounds-first sampled decode to the displayed size
(office) or a 1024px cap (pdf stamps, placed 150pt wide).
Placeholder and error behaviour preserved - the loading state
split keeps the [Image] label for genuine decode failures only,
caught by a rendering test.

Also already in HEAD via the a11y commit's weather files:
WeatherRefreshWorker's hourly refresh had no Constraints at
all; it now requires NetworkType.CONNECTED (matching small
hourly syncs like email, not the UNMETERED reserved for large
downloads), with policy UPDATE so existing installs pick it up.

Verified: office 1063, pdf 279, weather 291 tests, 0 failures.

Diff

office/src/main/java/com/vayunmathur/office/ui/OdfImageView.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OdfImageView.kt b/office/src/main/java/com/vayunmathur/office/ui/OdfImageView.ktindex 5c9f790138..0483a8aa3c 100644--- a/office/src/main/java/com/vayunmathur/office/ui/OdfImageView.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/OdfImageView.kt@@ -1,11 +1,13 @@ package com.vayunmathur.office.ui +import android.graphics.Bitmap import android.graphics.BitmapFactory import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer@@ -18,7 +20,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf-import androidx.compose.runtime.remember+import androidx.compose.runtime.produceState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -28,7 +30,9 @@ import androidx.compose.ui.graphics.ColorMatrix import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.layout+import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp@@ -39,6 +43,8 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.odf.OdfImage import com.vayunmathur.office.R+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext  private fun Modifier.rotateForDisplay(degrees: Float): Modifier {     if (degrees == 0f) return this@@ -68,70 +74,112 @@ private fun OdfImage.effectFilter(): ColorFilter? = when (colorMode) {     else -> null } +/**+ * Decode [data] down-sampled to roughly [reqWidthPx] x [reqHeightPx]: a+ * bounds-only first pass picks the largest power-of-two `inSampleSize` that+ * keeps both dimensions at or above the requested size, so a multi-megapixel+ * embedded photo never allocates a full-size bitmap for a small frame.+ * Returns null for empty/undecodable data, matching the previous behaviour.+ */+internal fun decodeSampledBitmap(data: ByteArray, reqWidthPx: Int, reqHeightPx: Int): Bitmap? {+    if (data.isEmpty()) return null+    return try {+        val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+        BitmapFactory.decodeByteArray(data, 0, data.size, bounds)+        if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null+        val reqW = reqWidthPx.coerceAtLeast(1)+        val reqH = reqHeightPx.coerceAtLeast(1)+        var sample = 1+        while (bounds.outWidth / (sample * 2) >= reqW && bounds.outHeight / (sample * 2) >= reqH) {+            sample *= 2+        }+        val opts = BitmapFactory.Options().apply { inSampleSize = sample }+        BitmapFactory.decodeByteArray(data, 0, data.size, opts)+    } catch (_: Exception) { null }+}++/** Decode state for [OdfImageView]: the placeholder label only appears once decoding has finished and failed. */+private sealed interface SampledDecode {+    data object Loading : SampledDecode+    data class Done(val bitmap: Bitmap?) : SampledDecode+}+ @Composable fun OdfImageView(image: OdfImage, modifier: Modifier = Modifier) {-    val bitmap = remember(image.path, image.imageData.size) {-        if (image.imageData.isNotEmpty()) try { BitmapFactory.decodeByteArray(-            image.imageData,-            0,-            image.imageData.size) } catch (_: Exception) { null } else null-    }-    if (bitmap != null) {-        val rot = Modifier.rotateForDisplay(image.rotationDegrees)-        val imgAlpha = image.alphaValue()-        val imgFilter = image.effectFilter()-        val hasCrop =-            image.cropLeftPct > 0f || image.cropTopPct > 0f || image.cropRightPct > 0f || image.cropBottomPct > 0f-        if (hasCrop) {-            // Non-destructive crop: draw only the visible source rectangle, scaled to fill. (Phase 5)-            val bw = bitmap.width; val bh = bitmap.height-            val visW = (1f - image.cropLeftPct - image.cropRightPct).coerceIn(0.05f, 1f)-            val visH = (1f - image.cropTopPct - image.cropBottomPct).coerceIn(0.05f, 1f)-            val srcX = (image.cropLeftPct * bw).toInt().coerceIn(0, bw - 1)-            val srcY = (image.cropTopPct * bh).toInt().coerceIn(0, bh - 1)-            val srcW = (visW * bw).toInt().coerceIn(1, bw - srcX)-            val srcH = (visH * bh).toInt().coerceIn(1, bh - srcY)-            val aspect = (srcW.toFloat() / srcH).coerceIn(0.1f, 10f)-            val img = bitmap.asImageBitmap()-            val sized = if (image.width > 0f && image.height > 0f)-                modifier.width((image.width * (160f / 96f)).coerceAtMost(700f).dp).aspectRatio(aspect)-            else modifier.fillMaxWidth().aspectRatio(aspect.coerceIn(0.3f, 4f))-            Canvas(sized.then(rot).padding(vertical = 4.dp)) {-                drawImage(-                    image = img,-                    srcOffset = IntOffset(srcX, srcY),-                    srcSize = IntSize(srcW, srcH),-                    dstOffset = IntOffset.Zero,-                    dstSize = IntSize(size.width.toInt().coerceAtLeast(1), size.height.toInt().coerceAtLeast(1)),-                    alpha = imgAlpha,-                    colorFilter = imgFilter-                )+    BoxWithConstraints(modifier) {+        val density = LocalDensity.current.density+        val reqWidthPx = if (maxWidth == Dp.Infinity) 1024 else (maxWidth.value * density).toInt().coerceAtLeast(1)+        // Scrolling containers give an unbounded height; the width is the binding+        // constraint there (aspect is clamped below), so sample against it.+        val reqHeightPx = if (maxHeight == Dp.Infinity) reqWidthPx else (maxHeight.value * density).toInt().coerceAtLeast(1)+        val decoded by produceState<SampledDecode>(+            if (image.imageData.isEmpty()) SampledDecode.Done(null) else SampledDecode.Loading,+            image.path, image.imageData.size, reqWidthPx, reqHeightPx) {+            if (image.imageData.isNotEmpty()) {+                value = SampledDecode.Done(withContext(Dispatchers.IO) {+                    decodeSampledBitmap(image.imageData, reqWidthPx, reqHeightPx)+                })             }-            return         }-        val useExplicit = image.width > 0f && image.height > 0f-        if (useExplicit) {-            // Honor the frame's svg:width/height (px@96dpi -> dp), capped to a readable width. (A2)-            val widthDp = (image.width * (160f / 96f)).coerceAtMost(700f)-            val aspect = (image.width / image.height).coerceIn(0.1f, 10f)-            Image(-                bitmap = bitmap.asImageBitmap(), contentDescription = null,-                modifier = modifier.width(widthDp.dp).aspectRatio(aspect).then(rot).padding(vertical = 4.dp),-                contentScale = ContentScale.Fit, alpha = imgAlpha, colorFilter = imgFilter-            )+        val bitmap = (decoded as? SampledDecode.Done)?.bitmap+        if (bitmap != null) {+            val rot = Modifier.rotateForDisplay(image.rotationDegrees)+            val imgAlpha = image.alphaValue()+            val imgFilter = image.effectFilter()+            val hasCrop =+                image.cropLeftPct > 0f || image.cropTopPct > 0f || image.cropRightPct > 0f || image.cropBottomPct > 0f+            if (hasCrop) {+                // Non-destructive crop: draw only the visible source rectangle, scaled to fill. (Phase 5)+                val bw = bitmap.width; val bh = bitmap.height+                val visW = (1f - image.cropLeftPct - image.cropRightPct).coerceIn(0.05f, 1f)+                val visH = (1f - image.cropTopPct - image.cropBottomPct).coerceIn(0.05f, 1f)+                val srcX = (image.cropLeftPct * bw).toInt().coerceIn(0, bw - 1)+                val srcY = (image.cropTopPct * bh).toInt().coerceIn(0, bh - 1)+                val srcW = (visW * bw).toInt().coerceIn(1, bw - srcX)+                val srcH = (visH * bh).toInt().coerceIn(1, bh - srcY)+                val aspect = (srcW.toFloat() / srcH).coerceIn(0.1f, 10f)+                val img = bitmap.asImageBitmap()+                val sized = if (image.width > 0f && image.height > 0f)+                    Modifier.width((image.width * (160f / 96f)).coerceAtMost(700f).dp).aspectRatio(aspect)+                else Modifier.fillMaxWidth().aspectRatio(aspect.coerceIn(0.3f, 4f))+                Canvas(sized.then(rot).padding(vertical = 4.dp)) {+                    drawImage(+                        image = img,+                        srcOffset = IntOffset(srcX, srcY),+                        srcSize = IntSize(srcW, srcH),+                        dstOffset = IntOffset.Zero,+                        dstSize = IntSize(size.width.toInt().coerceAtLeast(1), size.height.toInt().coerceAtLeast(1)),+                        alpha = imgAlpha,+                        colorFilter = imgFilter+                    )+                }+            } else if (image.width > 0f && image.height > 0f) {+                // Honor the frame's svg:width/height (px@96dpi -> dp), capped to a readable width. (A2)+                val widthDp = (image.width * (160f / 96f)).coerceAtMost(700f)+                val aspect = (image.width / image.height).coerceIn(0.1f, 10f)+                Image(+                    bitmap = bitmap.asImageBitmap(), contentDescription = null,+                    modifier = Modifier.width(widthDp.dp).aspectRatio(aspect).then(rot).padding(vertical = 4.dp),+                    contentScale = ContentScale.Fit, alpha = imgAlpha, colorFilter = imgFilter+                )+            } else {+                val aspect = if (bitmap.height > 0) bitmap.width.toFloat() / bitmap.height.toFloat() else 1.5f+                Image(+                    bitmap = bitmap.asImageBitmap(), contentDescription = null,+                    modifier = Modifier.fillMaxWidth().aspectRatio(aspect.coerceIn(+                        0.3f,+                        4f)).then(rot).padding(vertical = 4.dp),+                    contentScale = ContentScale.Fit, alpha = imgAlpha, colorFilter = imgFilter+                )+            }         } else {-            val aspect = if (bitmap.height > 0) bitmap.width.toFloat() / bitmap.height.toFloat() else 1.5f-            Image(-                bitmap = bitmap.asImageBitmap(), contentDescription = null,-                modifier = modifier.fillMaxWidth().aspectRatio(aspect.coerceIn(-                    0.3f,-                    4f)).then(rot).padding(vertical = 4.dp),-                contentScale = ContentScale.Fit, alpha = imgAlpha, colorFilter = imgFilter-            )-        }-    } else {-        Box(modifier.fillMaxWidth().height(120.dp).padding(vertical = 4.dp).background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center) {-            Text(stringResource(R.string.image), color = MaterialTheme.colorScheme.onSurfaceVariant)+            // Placeholder box while decoding; the label appears once decoding+            // has finished, for empty/undecodable data (the previous error UI).+            Box(Modifier.fillMaxWidth().height(120.dp).padding(vertical = 4.dp).background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center) {+                if (decoded is SampledDecode.Done) {+                    Text(stringResource(R.string.image), color = MaterialTheme.colorScheme.onSurfaceVariant)+                }+            }         }     } }
office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt b/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.ktindex 5dec384803..96635051cd 100644--- a/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt@@ -18,8 +18,9 @@ import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState-import android.graphics.BitmapFactory+import android.graphics.Bitmap import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale@@ -33,10 +34,13 @@ import com.vayunmathur.library.ui.IconCrop import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Dp import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor@@ -56,6 +60,8 @@ import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.library.ui.odf.OdfImage import com.vayunmathur.library.ui.odf.OdfTableCell import com.vayunmathur.office.R+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext  import com.vayunmathur.office.platform.firstSpan // --- Text Document (continuous editor) ---@@ -197,17 +203,28 @@ fun TextDocumentView(  @Composable private fun FullScreenImage(image: OdfImage, onCrop: (() -> Unit)? = null, onDismiss: () -> Unit) {-    val bitmap = remember(-        image.path,-        image.imageData.size) { BitmapFactory.decodeByteArray(image.imageData, 0, image.imageData.size) }     Box(         Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.9f)).clickable { onDismiss() },         contentAlignment = Alignment.Center) {-        if (bitmap != null) Image(-            bitmap = bitmap.asImageBitmap(),-            contentDescription = null,-            modifier = Modifier.fillMaxWidth().padding(16.dp),-            contentScale = ContentScale.Fit)+        BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+            val density = LocalDensity.current.density+            val reqWidthPx = if (maxWidth == Dp.Infinity) 1024 else (maxWidth.value * density).toInt().coerceAtLeast(1)+            val reqHeightPx = if (maxHeight == Dp.Infinity) reqWidthPx else (maxHeight.value * density).toInt().coerceAtLeast(1)+            val bitmap by produceState<Bitmap?>(+                null, image.path, image.imageData.size, reqWidthPx, reqHeightPx) {+                value = withContext(Dispatchers.IO) {+                    decodeSampledBitmap(image.imageData, reqWidthPx, reqHeightPx)+                }+            }+            // No image while decoding or for undecodable data, as before.+            bitmap?.let { decoded ->+                Image(+                    bitmap = decoded.asImageBitmap(),+                    contentDescription = null,+                    modifier = Modifier.fillMaxWidth().padding(16.dp),+                    contentScale = ContentScale.Fit)+            }+        }         if (onCrop != null) {             TextButton(onClick = onCrop, modifier = Modifier.align(Alignment.TopStart).padding(8.dp)) {                 IconCrop(tint = Color.White)
pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueContent.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueContent.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueContent.ktindex b29b1346bf..66b5896f15 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueContent.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueContent.kt@@ -15,7 +15,6 @@ import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState@@ -25,6 +24,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import com.vayunmathur.library.log.Log import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.adaptiveGridCells import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem@@ -142,7 +142,7 @@ fun CutGlueContent(                 )             } else {                 LazyVerticalGrid(-                    columns = GridCells.Fixed(3),+                    columns = adaptiveGridCells(100.dp),                     state = gridState,                     horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp),                     modifier = Modifier.fillMaxSize().padding(8.dp),
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerModels.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerModels.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerModels.ktindex 6666c4f44e..7572c48d3f 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerModels.kt@@ -34,6 +34,8 @@ import com.vayunmathur.library.ui.IconSquiggly import com.vayunmathur.library.ui.IconStrikethrough import com.vayunmathur.pdf.platform.SafePdfDocument import java.io.ByteArrayOutputStream+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext  internal sealed interface LoadState {     data object Loading : LoadState@@ -279,12 +281,43 @@ internal data class TextSession( ) internal class JpegImage(val bytes: ByteArray, val width: Int, val height: Int) -/** Read [uri] and re-encode it as JPEG for a stamp; null on failure. */-internal fun readAsJpeg(context: android.content.Context, uri: Uri): JpegImage? = runCatching {-    val bmp = context.contentResolver.openInputStream(uri)?.use {-        BitmapFactory.decodeStream(it)-    } ?: return null-    val out = ByteArrayOutputStream()-    bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 85, out)-    JpegImage(out.toByteArray(), bmp.width, bmp.height)-}.getOrNull()+/**+ * Longest edge a decoded stamp image needs. Stamps are placed 150 pt wide,+ * so this keeps ample resolution for print without decoding a full-size+ * photo (a 20 MP decode would commit ~80 MB before re-encoding).+ */+private const val MAX_STAMP_IMAGE_PX = 1024++/** Power-of-two sample size keeping both dimensions at or above [MAX_STAMP_IMAGE_PX] where possible. */+private fun stampSampleSize(width: Int, height: Int): Int {+    var sample = 1+    while (width / (sample * 2) >= MAX_STAMP_IMAGE_PX && height / (sample * 2) >= MAX_STAMP_IMAGE_PX) {+        sample *= 2+    }+    return sample+}++/**+ * Read [uri] and re-encode it as JPEG for a stamp; null on failure.+ * Runs on [Dispatchers.IO]: the stream read, the sampled decode (bounds+ * pass first, so large photos are never decoded at full size) and the+ * JPEG re-encode all happen off the main thread.+ */+internal suspend fun readAsJpeg(context: android.content.Context, uri: Uri): JpegImage? =+    withContext(Dispatchers.IO) {+        runCatching {+            val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+            context.contentResolver.openInputStream(uri)?.use {+                BitmapFactory.decodeStream(it, null, bounds)+            }+            val opts = BitmapFactory.Options().apply {+                inSampleSize = stampSampleSize(bounds.outWidth, bounds.outHeight)+            }+            val bmp = context.contentResolver.openInputStream(uri)?.use {+                BitmapFactory.decodeStream(it, null, opts)+            } ?: return@runCatching null+            val out = ByteArrayOutputStream()+            bmp.compress(android.graphics.Bitmap.CompressFormat.JPEG, 85, out)+            JpegImage(out.toByteArray(), bmp.width, bmp.height)+        }.getOrNull()+    }
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerState.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerState.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerState.ktindex 6f97c8a1a8..67f80de583 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerState.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerState.kt@@ -29,7 +29,9 @@ import com.vayunmathur.pdf.platform.editText import com.vayunmathur.pdf.platform.moveAnnotation import com.vayunmathur.pdf.platform.reattachAnnotation import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext  /**  * Mutable edit/search/session state for [SafePdfViewerScreen].@@ -260,7 +262,8 @@ internal class SafePdfViewerState(val scope: CoroutineScope) {         imageTarget = null         if (imageUri != null && doc != null && target != null) {             scope.launch {-                val jpeg = readAsJpeg(context, imageUri) ?: return@launch+                // Decode/re-encode off the main thread (as in CutGlueScreen).+                val jpeg = withContext(Dispatchers.IO) { readAsJpeg(context, imageUri) } ?: return@launch                 val (index, pt) = target                 // Default 150pt-wide stamp preserving aspect ratio.                 val w = 150f