pdf: compose only a window of pages in the viewer (#942)
- Commit
f77efe64770cfbdb67ae4cb8b7c3fe8c9bbbe043- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 18:14 UTC (1 day ago)
- Parents
fa42db1
Opening the reported 940-page book still cost O(page count) before the first page could draw. The descriptor open is mmap-backed and the search-index prewarm is already page-count gated, but SafePdfPageViewer composed one slot per page in a plain Column and every slot — decoded or placeholder — wrote its measured height into snapshot state that the O(page count) scroll geometry reads. A book therefore composed and measured ~940 boxes at open, each measurement invalidating the geometry its neighbours depended on, even though a slot outside the viewport can only ever report the width/ratio estimate the scroll state already assumes for it. Fix at the cause: SafePdfScrollState now exposes composedRange(), the visible range widened by three overscan pages per side, plus heightBefore()/heightAfter() spacers sized from the same estimates. SafePdfPageViewer composes only that bounded window (decoding as before, placeholders now drawn by the page item at the true aspect ratio) and collapses everything outside it into the two spacers. Scroll offsets, the scrubber and the total content height are unchanged: they were always computed from the scroll state's tops, never from composition. Opening is now the same handful of composed slots at 9 pages as at 900. The previous grey placeholder boxes for off-screen pages are gone; they were never on screen by definition. Regression: ScrollZoomGlyphTest.composedWindowStaysBoundedForHuge Documents pins the bounded window and the before+window+after == content-height invariant on a 940-page state (top and deep scroll); composedWindowCoversSmallDocumentsAndEmptyIsSafe pins whole-document composition for a small document and empty-state safety. Verified fresh in the worktree: ./gradlew :pdf:lint :pdf:lintVitalRelease :pdf:testDevUnitTest — BUILD SUCCESSFUL.
Diff
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.ktindex e9b1d167bf..3c91751617 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt@@ -2,7 +2,6 @@ package com.vayunmathur.pdf.ui import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween-import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.TransformableState import androidx.compose.foundation.gestures.detectTapGestures@@ -11,9 +10,9 @@ import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.gestures.transformable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf@@ -43,10 +42,14 @@ import kotlin.math.roundToInt /** * Zoomable page viewer shared by the compact body and the Expanded viewer slot. *- * One vertical truth: every page slot is always laid out, and [scroll] holds the- * single document offset driven by finger drags, pinch pans, the scrubber and- * jumps. Slots outside the viewport skip the native decode and draw a cheap- * placeholder box instead, so large documents stay light without a lazy list.+ * One vertical truth: [scroll] holds the single document offset driven by+ * finger drags, pinch pans, the scrubber and jumps. Only the bounded window+ * of pages around the viewport ([SafePdfScrollState.composedRange]) is+ * composed; every page before and after it collapses into one spacer apiece,+ * sized from the same height estimates the scroll geometry already uses, so+ * opening a document costs the same at 9 pages as at 900. Pages inside the+ * window decode natively; until a decode lands the page item draws its own+ * placeholder at the page's true aspect ratio. */ @Composable internal fun SafePdfPageViewer(@@ -72,8 +75,8 @@ internal fun SafePdfPageViewer( scroll.pageCount = state.pageCount val doc = bundle.document scroll.ratioAt = { doc?.knownAspectRatio(it) }- // Page-granular: recompose the list only when the visible set changes.- val visible by remember { derivedStateOf { scroll.visibleRange(zoom.zoom) } }+ // Page-granular: recompose the list only when the composed window changes.+ val window by remember { derivedStateOf { scroll.composedRange(zoom.zoom) } } // Plain outer box: the zoom transform below must not scale the page // scrubber, so the scrubber lives here as an unzoomed overlay.@@ -177,8 +180,17 @@ internal fun SafePdfPageViewer( modifier = Modifier.align(Alignment.Center).padding(24.dp), ) is LoadState.Loaded -> Column(Modifier.fillMaxWidth()) {- for (index in 0 until state.pageCount) {- if (index in visible) {+ val composed = window+ if (!composed.isEmpty()) {+ val density = androidx.compose.ui.platform.LocalDensity.current+ if (composed.first > 0) {+ Box(+ Modifier+ .fillMaxWidth()+ .height(with(density) { scroll.heightBefore(composed.first).toDp() })+ )+ }+ for (index in composed) { Box( Modifier .fillMaxWidth()@@ -222,17 +234,12 @@ internal fun SafePdfPageViewer( onAddPolyPoint = { pt -> state.addPolyPoint(index, pt) }, ) }- } else {- // Cheap placeholder: same footprint, no native decode.- val r = loadState.document.knownAspectRatio(index)?.takeIf { it > 0f }- ?: FALLBACK_PAGE_RATIO+ }+ if (composed.last < state.pageCount - 1) { Box( Modifier .fillMaxWidth()- .onSizeChanged { scroll.setMeasuredHeight(index, it.height) }- .padding(4.dp)- .aspectRatio(r)- .background(MaterialTheme.colorScheme.surfaceVariant)+ .height(with(density) { scroll.heightAfter(composed.last).toDp() }) ) } }
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfScrollState.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfScrollState.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfScrollState.ktindex caa2627e41..71c9baa4c7 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfScrollState.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfScrollState.kt@@ -18,10 +18,18 @@ internal const val FALLBACK_PAGE_RATIO = 612f / 792f * ([scrollPx]) shared by finger drags, pinch pans, the scrubber and programmatic * jumps, so no list scroll ever fights the zoom pan. *- * Every page slot is always laid out (so the total height is real) while the- * expensive decode only runs for slots inside [visibleRange] — place all the- * boxes, render only the visible pages. Heights come from measured slots,- * falling back to width/ratio estimates until a slot reports in.+ * Only the pages inside [composedRange] are ever composed; everything before+ * and after collapses into a single spacer each, sized from this state's own+ * height estimates. Composing one slot per page made opening cost scale with+ * the page count (a 940-page book composed and measured 940 boxes before the+ * first page could draw, each measurement writing snapshot state that+ * invalidated the O(page count) geometry below) even though slots outside+ * the viewport could only ever report the estimate [tops] already assumes:+ * an undecoded page's measured height IS its width/ratio estimate, so a+ * spacer of that height is the same footprint with no per-page work. The+ * total height stays real because [tops] never depended on composition.+ * Heights come from measured slots, falling back to width/ratio estimates+ * until a slot reports in. */ internal class SafePdfScrollState { var viewportSize by mutableStateOf(IntSize.Zero)@@ -123,6 +131,33 @@ internal class SafePdfScrollState { if (pageCount <= 0) return scrollTo(pageTop(index.coerceIn(0, pageCount - 1)), zoom) }++ /**+ * The only pages the viewer composes: [visibleRange] widened by+ * [COMPOSED_OVERSCAN_PAGES] on each side so a small scroll does not have+ * to compose (and start decoding) a page the instant it enters the+ * viewport. Bounded by the window size, never by the page count, so a+ * book of any length opens with the same handful of composed slots.+ */+ fun composedRange(zoom: Float): IntRange {+ if (pageCount <= 0) return IntRange.EMPTY+ val visible = visibleRange(zoom)+ val first = (visible.first - COMPOSED_OVERSCAN_PAGES).coerceAtLeast(0)+ val last = (visible.last + COMPOSED_OVERSCAN_PAGES).coerceAtMost(pageCount - 1)+ return if (last < first) IntRange.EMPTY else first..last+ }++ /** Height of everything before page [first], for the leading spacer. */+ fun heightBefore(first: Int): Float = pageTop(first)++ /** Height of everything after page [last], for the trailing spacer. */+ fun heightAfter(last: Int): Float =+ (contentHeightPx() - pageTop(last + 1)).coerceAtLeast(0f)++ private companion object {+ /** Pages composed (and decoded) beyond each edge of the visible set. */+ const val COMPOSED_OVERSCAN_PAGES = 3+ } } @Composable
pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.ktindex 8ef63a35af..ba17cde48a 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt@@ -64,6 +64,36 @@ class ScrollZoomGlyphTest { SafePdfScrollState().scrollToPage(1, 1f) // no pages, no crash } + @Test fun composedWindowStaysBoundedForHugeDocuments() {+ // The reported book (issue #942) at phone width: opening must+ // compose only a window of pages, never one slot per page.+ val s = scrollState(940)+ val window = s.composedRange(1f)+ assertTrue(window.contains(0))+ assertTrue(window.last - window.first < 20, "window=$window")+ val before = s.heightBefore(window.first)+ val after = s.heightAfter(window.last)+ val windowHeights = (window.first..window.last).sumOf { 792.0 }+ assertEquals(s.contentHeightPx().toDouble(), before + windowHeights + after, 1.0)+ // Deep in the book the window follows the scroll position, still bounded.+ s.scrollTo(500 * 792f, 1f)+ val deep = s.composedRange(1f)+ assertTrue(deep.contains(500), "window=$deep")+ assertTrue(deep.last - deep.first < 20, "window=$deep")+ assertEquals(+ s.contentHeightPx().toDouble(),+ s.heightBefore(deep.first) + (deep.last - deep.first + 1) * 792.0 + s.heightAfter(deep.last),+ 1.0,+ )+ }++ @Test fun composedWindowCoversSmallDocumentsAndEmptyIsSafe() {+ assertEquals(0..2, scrollState(3).composedRange(1f))+ assertTrue(SafePdfScrollState().composedRange(1f).isEmpty())+ assertEquals(0f, SafePdfScrollState().heightBefore(0))+ assertEquals(0f, SafePdfScrollState().heightAfter(0))+ }+ @Test fun zoomAroundKeepsCentroid() { val s = scrollState(5) s.scrollTo(500f, 1f)