Modern Apps git

← Modern-Apps.git

perf: window the agenda load; size image decodes to layout

Commit
489f16f086a93412ac9e7a73187b0cb226b5f985
Author
Vayun Mathur <[email protected]>
When
2026-11-20 19:41 UTC (15 days ago)
Parents
05595da
Calendar AgendaView composed 100,000 day items with no keys
and called loadInstances inside per-item produceState - roughly
one provider query per day on screen and one per day scrolled.
Items now have stable keys/contentType, and a single hoisted
produceState loads one ~62-day window (31-day pages, 10-day
prefetch over the visible indices), filing instances under
every span day in the window. Scroll anchoring unchanged.

AsyncImage decoded plain models at up to 4096px regardless of
thumbnail size - 68 of 72 call sites passed no size. It now
derives the decode size from layout constraints (measured size
when constraints are unbounded), explicit sizes pass through
untouched, and Size.Original remains available.

Verified: calendar 311 tests (incl. new AgendaWindowTest),
library:image 54 (incl. DeriveDecodeSizeTest), photos compiles
unchanged against the new AsyncImage.

Diff

calendar/src/main/java/com/vayunmathur/calendar/ui/AgendaView.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/AgendaView.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/AgendaView.ktindex 58f49feec2..ee11fdf389 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/AgendaView.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/AgendaView.kt@@ -13,6 +13,7 @@ import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember@@ -39,6 +40,61 @@ import kotlinx.datetime.todayIn import kotlin.time.Clock import kotlin.time.Instant +/** Total scrollable days; index [AGENDA_INITIAL_INDEX] is the anchor day. */+internal const val AGENDA_TOTAL_DAYS = 100_000++/** Index of the anchor day; the list can scroll ~137 years either way. */+internal const val AGENDA_INITIAL_INDEX = 50_000++/**+ * Days per instance-load page. The visible window is quantized to whole pages,+ * so scrolling within a page never re-queries the provider: one [loadInstances]+ * call serves every day on the page instead of one call per composed day.+ */+internal const val AGENDA_PAGE_DAYS = 31++/** Extra days loaded beyond the visible items on each side of the window. */+internal const val AGENDA_PREFETCH_DAYS = 10++/** Content type shared by every agenda day row (all rows have identical structure). */+internal const val AGENDA_DAY_CONTENT_TYPE = "agenda_day"++/**+ * Item indices whose instances must be loaded for a list currently showing+ * [firstVisible]..[lastVisible]: the visible span widened by+ * [AGENDA_PREFETCH_DAYS] on both sides, then rounded outward to whole+ * [AGENDA_PAGE_DAYS] pages and clamped to the list bounds.+ */+internal fun agendaWindowIndices(firstVisible: Int, lastVisible: Int): IntRange {+    val from = firstVisible - AGENDA_PREFETCH_DAYS+    val to = lastVisible + AGENDA_PREFETCH_DAYS+    val start = (from / AGENDA_PAGE_DAYS) * AGENDA_PAGE_DAYS+    val end = ((to / AGENDA_PAGE_DAYS) + 1) * AGENDA_PAGE_DAYS - 1+    return start.coerceAtLeast(0)..end.coerceAtMost(AGENDA_TOTAL_DAYS - 1)+}++/**+ * Expands [instances] into per-day lists for the window+ * [windowStart, windowEndExclusive): each instance is filed under every one of+ * its span days inside the window, sorted by start time within each day. Days+ * with no instances are absent (callers use an empty list). Doing the span-day+ * expansion once here keeps the per-item filter out of composition.+ */+internal fun groupInstancesByDay(+    instances: List<Instance>,+    windowStart: LocalDate,+    windowEndExclusive: LocalDate,+): Map<LocalDate, List<Instance>> {+    val byDay = mutableMapOf<LocalDate, MutableList<Instance>>()+    for (instance in instances.sortedBy { it.startDateTime }) {+        for (day in instance.spanDays) {+            if (day < windowStart || day >= windowEndExclusive) continue+            byDay.getOrPut(day) { mutableListOf() }.add(instance)+        }+    }+    return byDay+}+ @Composable fun AgendaView(     context: android.content.Context,@@ -51,10 +107,46 @@ fun AgendaView(     onEventClick: (Instance) -> Unit,     onDateViewingChanged: (LocalDate) -> Unit ) {-    val initialIndex = 50000+    val initialIndex = AGENDA_INITIAL_INDEX     val listState = rememberLazyListState(initialIndex)     // New rows have no id yet and can't be looked up; drop them instead of crashing.     val vEventsByID = remember(events) { events.mapNotNull { e -> e.id?.let { id -> id to e } }.toMap() }+    val today = remember { Clock.System.todayIn(TimeZone.currentSystemDefault()) }++    // The quantized window of item indices to have instances loaded for. Derived+    // from the layout info so it only changes when scrolling crosses a page+    // boundary, not on every composed day or scroll frame. Before the first+    // layout there are no visible items yet; centre on the initial index.+    val windowIndices by remember {+        derivedStateOf {+            val visible = listState.layoutInfo.visibleItemsInfo+            if (visible.isEmpty()) {+                agendaWindowIndices(initialIndex, initialIndex)+            } else {+                agendaWindowIndices(visible.first().index, visible.last().index)+            }+        }+    }+    val windowStart = anchorDate.plus(DatePeriod(days = windowIndices.first - initialIndex))+    val windowEndExclusive = anchorDate.plus(DatePeriod(days = windowIndices.last + 1 - initialIndex))++    // One provider query per window (per events/visibility change), grouped by+    // day up front. The previous per-item produceState ran one query per+    // composed day — a day spanning the viewport edge plus prefetch rows meant+    // ~a dozen overlapping queries for what is now a single window query.+    val instancesByDay by produceState<Map<LocalDate, List<Instance>>>(+        emptyMap(),+        windowStart,+        windowEndExclusive,+        events,+        calendarVisibility,+    ) {+        val loaded = loadInstances(+            windowStart.atStartOfDayIn(TimeZone.currentSystemDefault()),+            windowEndExclusive.atStartOfDayIn(TimeZone.currentSystemDefault()),+        )+        value = groupInstancesByDay(loaded, windowStart, windowEndExclusive)+    }      LaunchedEffect(listState) {         snapshotFlow { listState.firstVisibleItemIndex }.collect { index ->@@ -75,16 +167,13 @@ fun AgendaView(     }      LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {-        items(100000) { index ->+        items(+            count = AGENDA_TOTAL_DAYS,+            key = { index -> anchorDate.plus(DatePeriod(days = index - initialIndex)).toEpochDays() },+            contentType = { AGENDA_DAY_CONTENT_TYPE },+        ) { index ->             val date = anchorDate.plus(DatePeriod(days = index - initialIndex))-            val dayInstances by produceState(emptyList<Instance>(), date, events, calendarVisibility) {-                value = loadInstances(-                    date.atStartOfDayIn(TimeZone.currentSystemDefault()),-                    date.plus(DatePeriod(days = 1)).atStartOfDayIn(TimeZone.currentSystemDefault())-                ).sortedBy { it.startDateTime }-            }--            val today = remember { Clock.System.todayIn(TimeZone.currentSystemDefault()) }+            val dayInstances = instancesByDay[date].orEmpty()             val isToday = date == today              Column(Modifier.fillMaxWidth().then(if (isToday) Modifier.background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.2f)) else Modifier)) {@@ -94,7 +183,7 @@ fun AgendaView(                     style = MaterialTheme.typography.titleMedium,                     color = if (isToday) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface                 )-                dayInstances.filter { date in it.spanDays }.forEach { instance ->+                dayInstances.forEach { instance ->                     // Skip instances whose event was just deleted (sync-adapter delete                     // semantics) instead of crashing.                     val ev = vEventsByID[instance.eventID] ?: return@forEach
calendar/src/test/java/com/vayunmathur/calendar/ui/AgendaWindowTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/AgendaWindowTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/AgendaWindowTest.ktnew file mode 100644index 0000000000..61d6c0d204--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/ui/AgendaWindowTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.calendar.ui++import com.vayunmathur.calendar.data.Instance+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class AgendaWindowTest {++    private fun midnightUtc(date: String): Long =+        LocalDate.parse(date).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()++    private fun allDayInstance(id: Long, beginDate: String, endDateExclusive: String) = Instance(+        id = id,+        eventID = id,+        begin = midnightUtc(beginDate),+        end = midnightUtc(endDateExclusive),+        timezone = "UTC",+        allDay = true,+        eventTitle = "Test $id",+        color = 0,+        rrule = null,+    )++    @Test+    fun `window widens visible span by prefetch and quantizes to whole pages`() {+        val window = agendaWindowIndices(firstVisible = 50_000, lastVisible = 50_006)+        // Start of the 31-day page containing (50000 - 10), end of the page+        // containing (50006 + 10): scrolling inside the page must not move it.+        assertEquals(49_972, window.first)+        assertEquals(50_033, window.last)+        assertEquals(window, agendaWindowIndices(firstVisible = 50_001, lastVisible = 50_006))+        assertEquals(window, agendaWindowIndices(firstVisible = 50_010, lastVisible = 50_016))+        assertEquals(window, agendaWindowIndices(firstVisible = 49_990, lastVisible = 49_995))+    }++    @Test+    fun `window clamps to list bounds`() {+        val atStart = agendaWindowIndices(firstVisible = 0, lastVisible = 3)+        assertEquals(0, atStart.first)+        val atEnd = agendaWindowIndices(+            firstVisible = AGENDA_TOTAL_DAYS - 3,+            lastVisible = AGENDA_TOTAL_DAYS - 1,+        )+        assertEquals(AGENDA_TOTAL_DAYS - 1, atEnd.last)+        assertTrue(atEnd.first <= atEnd.last)+    }++    @Test+    fun `window covers at least one full page`() {+        val window = agendaWindowIndices(firstVisible = 123, lastVisible = 123)+        assertTrue(window.last - window.first + 1 >= AGENDA_PAGE_DAYS)+    }++    @Test+    fun `grouping files a multi-day instance under each span day in the window`() {+        val instance = allDayInstance(1L, "2026-07-15", "2026-07-18") // spans 15, 16, 17+        val byDay = groupInstancesByDay(+            listOf(instance),+            windowStart = LocalDate.parse("2026-07-16"),+            windowEndExclusive = LocalDate.parse("2026-07-17"),+        )+        // Days outside the window are clipped even though the instance spans them.+        assertEquals(setOf(LocalDate.parse("2026-07-16")), byDay.keys)+        assertEquals(listOf(instance), byDay[LocalDate.parse("2026-07-16")])+    }++    @Test+    fun `grouping sorts each day by start and omits empty days`() {+        val later = allDayInstance(2L, "2026-07-16", "2026-07-17")+        val earlier = allDayInstance(1L, "2026-07-15", "2026-07-17") // spans 15 + 16+        val byDay = groupInstancesByDay(+            listOf(later, earlier),+            windowStart = LocalDate.parse("2026-07-15"),+            windowEndExclusive = LocalDate.parse("2026-07-18"),+        )+        assertEquals(listOf(earlier), byDay[LocalDate.parse("2026-07-15")])+        assertEquals(listOf(earlier, later), byDay[LocalDate.parse("2026-07-16")])+        assertEquals(null, byDay[LocalDate.parse("2026-07-17")])+    }++    @Test+    fun `grouping of no instances is empty`() {+        val byDay = groupInstancesByDay(+            emptyList(),+            windowStart = LocalDate.parse("2026-07-15"),+            windowEndExclusive = LocalDate.parse("2026-07-16"),+        )+        assertTrue(byDay.isEmpty())+    }+}
library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt b/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.ktindex b6015552d1..8af4679a79 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt@@ -4,11 +4,13 @@ import android.content.Context import android.graphics.Bitmap import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.Image-import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints 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.draw.alpha@@ -16,10 +18,13 @@ import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.IntSize import com.vayunmathur.library.image.ImageLoader import com.vayunmathur.library.image.ImageRequest import com.vayunmathur.library.image.ImageResult+import com.vayunmathur.library.image.Size  /**  * Coil-like AsyncImage backed by our ImageLoader (HttpURLConnection + custom caches + SVG + Video).@@ -27,6 +32,14 @@ import com.vayunmathur.library.image.ImageResult  * Supported model types (Any?): Uri, String URL, java.io.File, ByteArray, Bitmap, ImageRequest.  * Mirrors signature used across codebase:  * `AsyncImage(model, contentDescription, modifier, contentScale, colorFilter, onState)`+ *+ * Decode size: a request with no explicit size used to decode at up to+ * [com.vayunmathur.library.image.decoders.BitmapDecoder.MAX_ORIGINAL_DIMENSION]+ * px even into a 48.dp thumbnail, because most call sites pass a plain model and+ * rely on the default. Like Coil, the decode size is now derived from this+ * composable's layout constraints (see [deriveDecodeSize]); callers that pass an+ * explicit size — including [Size.Original] when they truly want the full+ * image — are left untouched.  */ @Composable fun AsyncImage(@@ -43,27 +56,53 @@ fun AsyncImage(     val context = LocalContext.current     val loader = imageLoader ?: remember(context) { ImageLoader.get(context) } -    val request = rememberImageRequest(model, context)+    val baseRequest = rememberImageRequest(model, context) -    // Synchronous memory-cache probe. On a hit the bitmap is available before the-    // first frame, so a scrolled-in item paints immediately instead of showing an-    // empty box for a frame and re-running its crossfade over an image that was-    // already in memory.-    val seeded = rememberSeededBitmap(request, loader)+    // Fallback decode-size source for the case where the constraints are+    // unbounded (e.g. an infinite-width scroll row): the size this composable+    // was actually laid out at, known after the first layout pass.+    var measuredSize by remember { mutableStateOf(IntSize.Zero) } -    val bitmapState = rememberAsyncBitmap(request, seeded, loader, onState)+    BoxWithConstraints(+        modifier = modifier.onSizeChanged { measuredSize = it },+        contentAlignment = alignment,+    ) {+        val derivedSize = deriveDecodeSize(+            explicitSize = baseRequest?.size,+            constraintWidth = constraints.maxWidth,+            constraintHeight = constraints.maxHeight,+            measuredWidth = measuredSize.width,+            measuredHeight = measuredSize.height,+        )+        val request = remember(baseRequest, derivedSize) {+            when {+                baseRequest == null -> null+                // An explicit size (a real size, or Size.Original from a caller+                // that truly wants the full image) always wins.+                baseRequest.size != null -> baseRequest+                derivedSize != null -> baseRequest.copy(size = derivedSize)+                else -> baseRequest+            }+        } -    val bitmap = bitmapState.value+        // Synchronous memory-cache probe. On a hit the bitmap is available before the+        // first frame, so a scrolled-in item paints immediately instead of showing an+        // empty box for a frame and re-running its crossfade over an image that was+        // already in memory.+        val seeded = rememberSeededBitmap(request, loader) -    // Crossfade alpha if requested-    val shouldCrossfade = request?.crossfade == true-    val targetAlpha = if (bitmap != null) alpha else 0f-    val animatedAlpha by animateFloatAsState(-        targetValue = if (shouldCrossfade) targetAlpha else alpha,-        label = "asyncImageCrossfade"-    )+        val bitmapState = rememberAsyncBitmap(request, seeded, loader, onState)++        val bitmap = bitmapState.value++        // Crossfade alpha if requested+        val shouldCrossfade = request?.crossfade == true+        val targetAlpha = if (bitmap != null) alpha else 0f+        val animatedAlpha by animateFloatAsState(+            targetValue = if (shouldCrossfade) targetAlpha else alpha,+            label = "asyncImageCrossfade"+        ) -    Box(modifier = modifier, contentAlignment = alignment) {         if (bitmap != null) {             // Use Android-like scaling; honor colorFilter and contentScale             Image(@@ -80,6 +119,33 @@ fun AsyncImage(     } } +/**+ * The decode size for a request, or null to leave the request unsized.+ *+ * An [explicitSize] set by the caller (including [Size.Original]) is returned+ * unchanged. Otherwise the layout constraints win when both dimensions are+ * bounded ([constraintWidth]/[constraintHeight] are pixels;+ * [Int.MAX_VALUE] means unbounded), then the measured layout size, then null —+ * unsized, in which case the decoder still caps the longest edge at its+ * original-size limit rather than decoding without bound.+ */+internal fun deriveDecodeSize(+    explicitSize: Size?,+    constraintWidth: Int,+    constraintHeight: Int,+    measuredWidth: Int,+    measuredHeight: Int,+): Size? {+    if (explicitSize != null) return explicitSize+    if (constraintWidth in 1 until Int.MAX_VALUE && constraintHeight in 1 until Int.MAX_VALUE) {+        return Size(constraintWidth, constraintHeight)+    }+    if (measuredWidth > 0 && measuredHeight > 0) {+        return Size(measuredWidth, measuredHeight)+    }+    return null+}+ @Composable private fun rememberImageRequest(model: Any?, context: Context): ImageRequest? =     remember(model) {
library/image/src/test/java/com/vayunmathur/library/image/compose/DeriveDecodeSizeTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/compose/DeriveDecodeSizeTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/compose/DeriveDecodeSizeTest.ktnew file mode 100644index 0000000000..b6293f6b34--- /dev/null+++ b/library/image/src/test/java/com/vayunmathur/library/image/compose/DeriveDecodeSizeTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.library.image.compose++import com.vayunmathur.library.image.Size+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class DeriveDecodeSizeTest {++    @Test+    fun `explicit size always wins over layout`() {+        assertEquals(+            Size(256, 256),+            deriveDecodeSize(Size(256, 256), constraintWidth = 1080, constraintHeight = 800, measuredWidth = 400, measuredHeight = 300),+        )+    }++    @Test+    fun `explicit original size is preserved so callers can still request the full image`() {+        assertEquals(+            Size.Original,+            deriveDecodeSize(Size.Original, constraintWidth = 1080, constraintHeight = 800, measuredWidth = 400, measuredHeight = 300),+        )+    }++    @Test+    fun `plain models derive their decode size from bounded constraints`() {+        assertEquals(+            Size(320, 240),+            deriveDecodeSize(null, constraintWidth = 320, constraintHeight = 240, measuredWidth = 0, measuredHeight = 0),+        )+    }++    @Test+    fun `unbounded constraints fall back to the measured layout size`() {+        assertEquals(+            Size(180, 180),+            deriveDecodeSize(null, constraintWidth = Int.MAX_VALUE, constraintHeight = 240, measuredWidth = 180, measuredHeight = 180),+        )+        assertEquals(+            Size(180, 180),+            deriveDecodeSize(null, constraintWidth = 320, constraintHeight = Int.MAX_VALUE, measuredWidth = 180, measuredHeight = 180),+        )+    }++    @Test+    fun `no usable layout size leaves the request unsized`() {+        assertNull(deriveDecodeSize(null, constraintWidth = Int.MAX_VALUE, constraintHeight = Int.MAX_VALUE, measuredWidth = 0, measuredHeight = 0))+        assertNull(deriveDecodeSize(null, constraintWidth = 0, constraintHeight = 0, measuredWidth = 0, measuredHeight = 0))+        assertNull(deriveDecodeSize(null, constraintWidth = 320, constraintHeight = Int.MAX_VALUE, measuredWidth = 0, measuredHeight = 0))+    }+}