Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
WIP: xlsx grid perf work in progress (rate-limited mid-task)
Chethan6168a03b3b00db4
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetGrid.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetGrid.ktindex f2d78f8..4f0a5aa 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetGrid.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetGrid.kt@@ -20,11 +20,15 @@ import androidx.compose.foundation.lazy.LazyListStateimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.MutableFloatState+import androidx.compose.runtime.State+import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipToBoundsimport androidx.compose.ui.draw.drawBehind@@ -39,6 +43,7 @@ import androidx.compose.ui.graphics.toArgbimport androidx.compose.ui.input.pointer.PointerEventPassimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.layout.layoutimport androidx.compose.ui.layout.onGloballyPositionedimport androidx.compose.ui.layout.positionInRootimport androidx.compose.ui.platform.LocalDensity@@ -50,6 +55,7 @@ import com.chethan616.clearpdf.utils.xlsx.XlsxPainterimport com.chethan616.clearpdf.utils.xlsx.XlsxRefsimport com.chethan616.clearpdf.utils.xlsx.XlsxSheetimport kotlin.math.abs+import kotlin.math.roundToInt/** The selected range plus the cell typing goes into. */data class GridSelection(val anchorR: Int, val anchorC: Int, val range: CellRange) {@@ -62,14 +68,27 @@ data class GridSelection(val anchorR: Int, val anchorC: Int, val range: CellRang}}-/** Colours for the grid chrome (headers, selection), derived from the app theme. */+/**+ * Colours for the grid chrome (headers, selection), derived from the app theme. The ARGB forms are+ * resolved once here: the gutter and header paint with `android.graphics`, and converting (or+ * `copy(alpha)`-ing) a Compose colour per row per frame was pure allocation on the draw path.+ */class GridColors(val surface: Color,val headerBand: Color,val headerText: Color,val headerDivider: Color,val accent: Color-)+) {+ val headerBandArgb = headerBand.toArgb()+ val headerTextArgb = headerText.toArgb()+ val headerDividerArgb = headerDivider.toArgb()+ val accentArgb = accent.toArgb()+ /** Header / gutter band behind a selected column or row. */+ val selBandArgb = accent.copy(alpha = 0.14f).toArgb()+ /** …and behind a whole selected column or row. */+ val wholeSelBandArgb = accent.copy(alpha = 0.30f).toArgb()+}/*** The spreadsheet grid.@@ -79,6 +98,11 @@ class GridColors(* scrolling is a plain scroll offset read only in the draw phase, so panning sideways never* recomposes or re-lays-out a row. Frozen rows sit above the list and frozen columns are painted in* place by the painter; the column-letter header and the row-number gutter are sticky.+ *+ * Zoom follows the same rule: it lives in [zoom] and is read only in layout (row heights), draw+ * and gesture code, through [Geo]. A pinch used to write a `var zoom` the whole viewer read during+ * composition, so every pointer event of a pinch recomposed the entire screen and every visible row;+ * now it re-measures the rows and redraws, nothing more.*/@Composableinternal fun SpreadsheetGrid(@@ -86,7 +110,7 @@ internal fun SpreadsheetGrid(layout: SheetLayout,painter: XlsxPainter,version: Int,- zoom: Float,+ zoom: MutableFloatState,listState: LazyListState,scrollX: MutableFloatState,selection: GridSelection?,@@ -98,16 +122,12 @@ internal fun SpreadsheetGrid(onSelect: (GridSelection) -> Unit,onTapSelected: (Int, Int) -> Unit,onDropdown: (r: Int, c: Int, anchorInRoot: Rect) -> Unit,- onZoom: (Float) -> Unit,onColumnResize: (Int, Float) -> Unit,modifier: Modifier = Modifier) {val density = LocalDensity.current- val scale = density.density * zoomval headerH = with(density) { 28.dp.toPx() }val gutterW = with(density) { ((layout.nRows.toString().length * 7 + 22).dp).toPx() }- val frozenW = layout.frozenWidth * scale- val frozenH = layout.frozenHeight * scaleval fc = sheet.frozenCols.coerceAtMost(layout.nCols)val handleR = with(density) { 7.dp.toPx() }val chevronW = with(density) { 22.dp.toPx() }@@ -116,10 +136,15 @@ internal fun SpreadsheetGrid(val currentOnSelect by rememberUpdatedState(onSelect)val currentOnTapSelected by rememberUpdatedState(onTapSelected)val currentOnDropdown by rememberUpdatedState(onDropdown)- val currentOnZoom by rememberUpdatedState(onZoom)val currentOnResize by rememberUpdatedState(onColumnResize)val currentEdit by rememberUpdatedState(editMode)- val geo = rememberUpdatedState(Geo(layout, scale, frozenW, frozenH, fc, gutterW, headerH))+ // Geometry for the current zoom. A derived state, so it is only rebuilt when the zoom or the+ // layout really changes — the old `rememberUpdatedState(Geo(...))` handed every row a new object+ // on every recomposition of this function (a selection change, a keystroke in the formula bar),+ // which invalidated the draw of every visible row even when nothing about them had moved.+ val geo: State<Geo> = remember(layout, density, gutterW, headerH, fc, zoom) {+ derivedStateOf { Geo.of(layout, density.density * zoom.floatValue, fc, gutterW, headerH) }+ }var gridOrigin by remember { mutableStateOf(Offset.Zero) }/** Column being resized and its live width in Excel px. */@@ -132,27 +157,37 @@ internal fun SpreadsheetGrid(textSize = with(density) { 12.dp.toPx() }}}+ // Baseline offset of the header labels, measured once (fake-bold doesn't move the metrics).+ val headerTextDy = remember(headerPaint) { headerPaint.fontMetrics.let { -(it.ascent + it.descent) / 2f } }val bandPaint = remember { Paint() }+ // Row numbers and column letters, built once per label instead of once per row per frame.+ val labels = remember(layout) { GridLabels(layout.nRows, layout.nCols) }- // Horizontal pan: an offset in px, clamped to the scrollable width.- var viewportW by remember { mutableStateOf(0f) }- val maxScroll = ((layout.totalWidth - layout.frozenWidth) * scale - (viewportW - gutterW - frozenW)).coerceAtLeast(0f)- // Keep the scroll offset out of composition: a pointer pan updates it every frame and the- // previous read here subscribed the whole grid composable to every horizontal pixel.- LaunchedEffect(maxScroll) {- val current = scrollX.floatValue- if (current > maxScroll) scrollX.floatValue = maxScroll+ // Horizontal pan: an offset in px, clamped to the scrollable width. Width and offset are read+ // only in callbacks and draw lambdas, never in composition.+ val viewportW = remember { mutableFloatStateOf(0f) }+ fun maxScroll(g: Geo): Float =+ ((g.layout.totalWidth - g.layout.frozenWidth) * g.scale - (viewportW.floatValue - g.gutterW - g.frozenW)).coerceAtLeast(0f)+ LaunchedEffect(geo) {+ snapshotFlow { maxScroll(geo.value) }.collect { max ->+ if (scrollX.floatValue > max) scrollX.floatValue = max+ }}val hState = rememberScrollableState { delta ->val old = scrollX.floatValue- val next = (old - delta).coerceIn(0f, maxScroll)+ val next = (old - delta).coerceIn(0f, maxScroll(geo.value))scrollX.floatValue = nextold - next}fun rowRect(g: Geo, r: Int): Pair<Float, Float>? {- if (r < sheet.frozenRows) return g.layout.rowY[r] * g.scale to g.layout.rowY[r + 1] * g.scale- val first = listState.layoutInfo.visibleItemsInfo.firstOrNull() ?: return null+ if (r < sheet.frozenRows) return g.frozenTop(r) to g.frozenTop(r + 1)+ val visible = listState.layoutInfo.visibleItemsInfo+ val first = visible.firstOrNull() ?: return null+ // Exact for a row on screen. Item heights are whole pixels, so deriving a row's position by+ // summing the sheet's fractional heights drifted ~0.5 px per row and put the selection+ // frame visibly off its cell a screen further down.+ for (item in visible) if (item.key == r) return g.frozenH + item.offset to g.frozenH + item.offset + item.sizeval firstRow = g.layout.scrollRows.getOrNull(first.index) ?: return nullval top = g.frozenH + first.offset + (g.layout.rowY[r.coerceAtMost(g.layout.nRows)] - g.layout.rowY[firstRow]) * g.scaleval bottom = top + (g.layout.rowY[(r + 1).coerceAtMost(g.layout.nRows)] - g.layout.rowY[r.coerceAtMost(g.layout.nRows)]) * g.scale@@ -167,7 +202,11 @@ internal fun SpreadsheetGrid(/** Grid-body point → (row, col); col −1 = row gutter. Null below the last row. */fun hit(g: Geo, p: Offset): Pair<Int, Int>? {- val r = if (p.y < g.frozenH) g.layout.rowAt(p.y / g.scale) else {+ val r = if (p.y < g.frozenH) {+ var fr = 0+ while (fr < sheet.frozenRows - 1 && g.frozenTop(fr + 1) <= p.y) fr+++ fr+ } else {val y = p.y - g.frozenHval item = listState.layoutInfo.visibleItemsInfo.firstOrNull { y >= it.offset && y < it.offset + it.size } ?: return nullg.layout.scrollRows.getOrNull(item.index) ?: return null@@ -202,9 +241,9 @@ internal fun SpreadsheetGrid(Column(modifier.fillMaxSize()- .onGloballyPositioned { viewportW = it.size.width.toFloat(); gridOrigin = it.positionInRoot() }+ .onGloballyPositioned { viewportW.floatValue = it.size.width.toFloat(); gridOrigin = it.positionInRoot() }.scrollable(hState, Orientation.Horizontal)- .pointerInput(Unit) {+ .pointerInput(zoom) {// Pinch to zoom; single-finger gestures pass through to scrolling.awaitEachGesture {awaitFirstDown(requireUnconsumed = false)@@ -212,7 +251,10 @@ internal fun SpreadsheetGrid(val e = awaitPointerEvent()if (e.changes.count { it.pressed } >= 2) {val z = e.calculateZoom()- if (z != 1f) { currentOnZoom(z); e.changes.forEach { it.consume() } }+ if (z != 1f) {+ zoom.floatValue = (zoom.floatValue * z).coerceIn(0.5f, 2.5f)+ e.changes.forEach { it.consume() }+ }}} while (e.changes.any { it.pressed })}@@ -270,6 +312,7 @@ internal fun SpreadsheetGrid(val nc = cv.nativeCanvasnc.save()nc.clipRect(g.gutterW, 0f, size.width, size.height)+ val baseline = size.height / 2f + headerTextDyfun drawCol(c: Int) {val w = g.layout.colW(c) * g.scaleif (w <= 0f) return@@ -277,14 +320,13 @@ internal fun SpreadsheetGrid(if (x > size.width || x + w < g.gutterW) returnval inSel = sel != null && c in sel.range.c1..sel.range.c2if (inSel) {- bandPaint.color = colors.accent.copy(alpha = if (sel!!.isWholeColumn) 0.30f else 0.14f).toArgb()+ bandPaint.color = if (sel!!.isWholeColumn) colors.wholeSelBandArgb else colors.selBandArgbnc.drawRect(x, 0f, x + w, size.height, bandPaint)}- headerPaint.color = (if (inSel) colors.accent else colors.headerText).toArgb()+ headerPaint.color = if (inSel) colors.accentArgb else colors.headerTextArgbheaderPaint.isFakeBoldText = inSel- val fm = headerPaint.fontMetrics- nc.drawText(XlsxRefs.colLetter(c), x + w / 2f, size.height / 2f - (fm.ascent + fm.descent) / 2f, headerPaint)- bandPaint.color = colors.headerDivider.toArgb()+ nc.drawText(labels.col(c), x + w / 2f, baseline, headerPaint)+ bandPaint.color = colors.headerDividerArgbnc.drawRect(x + w - 1f, size.height * 0.22f, x + w, size.height * 0.78f, bandPaint)}// Scrolling columns, then frozen ones over them.@@ -371,11 +413,10 @@ internal fun SpreadsheetGrid(Column(Modifier.fillMaxSize()) {// Frozen rows: pinned above the scrolling list.for (r in 0 until sheet.frozenRows.coerceAtMost(layout.nRows)) {- val h = layout.rowH(r) * scale- if (h <= 0f) continue+ if (layout.rowH(r) <= 0f) continueSpacer(- Modifier.fillMaxWidth().height(with(density) { h.toDp() })- .drawBehind { drawGridRow(r, painter, layout, geo.value, scrollX.floatValue, colors, headerPaint, bandPaint, currentSelection) { m -> m.r1 == r } }+ Modifier.fillMaxWidth().rowHeight(layout, r, geo)+ .drawBehind { drawGridRow(r, painter, layout, geo.value, scrollX.floatValue, colors, headerPaint, headerTextDy, bandPaint, labels, currentSelection) { m -> m.r1 == r } })}LazyColumn(@@ -385,12 +426,11 @@ internal fun SpreadsheetGrid() {items(count = layout.scrollRows.size, key = { layout.scrollRows[it] }) { i ->val r = layout.scrollRows[i]- val h = layout.rowH(r) * scaleSpacer(- Modifier.fillMaxWidth().height(with(density) { h.toDp() })+ Modifier.fillMaxWidth().rowHeight(layout, r, geo).drawBehind {@Suppress("UNUSED_EXPRESSION") version- drawGridRow(r, painter, layout, geo.value, scrollX.floatValue, colors, headerPaint, bandPaint, currentSelection) { m ->+ drawGridRow(r, painter, layout, geo.value, scrollX.floatValue, colors, headerPaint, headerTextDy, bandPaint, labels, currentSelection) { m ->val firstRow = layout.scrollRows.getOrElse(listState.firstVisibleItemIndex) { 0 }r == maxOf(m.r1, firstRow, sheet.frozenRows)}@@ -399,14 +439,16 @@ internal fun SpreadsheetGrid(}}}- if (frozenH > 0f) {+ if (layout.frozenHeight > 0f) {Spacer(Modifier.fillMaxSize().drawBehind {- drawLine(colors.headerDivider, Offset(0f, frozenH), Offset(size.width, frozenH), 2f)+ val fh = geo.value.frozenH+ drawLine(colors.headerDivider, Offset(0f, fh), Offset(size.width, fh), 2f)})}- if (frozenW > 0f) {+ if (layout.frozenWidth > 0f) {Spacer(Modifier.fillMaxSize().drawBehind {- drawLine(colors.headerDivider, Offset(gutterW + frozenW, 0f), Offset(gutterW + frozenW, size.height), 2f)+ val g = geo.value+ drawLine(colors.headerDivider, Offset(g.gutterW + g.frozenW, 0f), Offset(g.gutterW + g.frozenW, size.height), 2f)})}@@ -417,15 +459,19 @@ internal fun SpreadsheetGrid(@Suppress("UNUSED_EXPRESSION") versionclipRect(g.gutterW) {if (matches.isNotEmpty()) {- val first = listState.firstVisibleItemIndex- val firstRow = layout.scrollRows.getOrElse(first) { 0 }- val lastRow = layout.scrollRows.getOrElse(first + listState.layoutInfo.visibleItemsInfo.size + 1) { layout.nRows }- for (m in matches) {- if (m.first !in (if (m.first < sheet.frozenRows) 0 else firstRow)..lastRow) continue- val rect = selectionRect(g, GridSelection.cell(m.first, m.second, sheet)) ?: continue- val cur = m == currentMatch- drawRect(colors.accent.copy(alpha = if (cur) 0.45f else 0.18f), rect.topLeft, rect.size)+ fun paint(m: Pair<Int, Int>) {+ val rect = selectionRect(g, GridSelection.cell(m.first, m.second, sheet)) ?: return+ drawRect(colors.accent.copy(alpha = if (m == currentMatch) 0.45f else 0.18f), rect.topLeft, rect.size)}+ // Matches come out of the scan sorted by row, so only the slice that is on+ // screen is visited — not all (up to 5 000) on every scroll frame.+ var i = 0+ while (i < matches.size && matches[i].first < sheet.frozenRows) paint(matches[i++])+ val visible = listState.layoutInfo.visibleItemsInfo+ val firstRow = (visible.firstOrNull()?.key as? Int) ?: 0+ val lastRow = (visible.lastOrNull()?.key as? Int) ?: layout.nRows+ var j = lowerBoundByRow(matches, maxOf(firstRow, sheet.frozenRows))+ while (j < matches.size && matches[j].first <= lastRow) paint(matches[j++])}val sel = currentSelection ?: return@clipRectval rect = selectionRect(g, sel) ?: return@clipRect@@ -467,16 +513,60 @@ internal fun SpreadsheetGrid(}}-/** Frozen geometry for one frame, captured so gesture handlers never see a stale layout. */+/** First index in [matches] (sorted by row) whose row is ≥ [row]. */+private fun lowerBoundByRow(matches: List<Pair<Int, Int>>, row: Int): Int {+ var lo = 0+ var hi = matches.size+ while (lo < hi) {+ val mid = (lo + hi) ushr 1+ if (matches[mid].first < row) lo = mid + 1 else hi = mid+ }+ return lo+}++/**+ * A row's height at the current zoom, read in the *measure* pass. A zoom change re-measures the+ * rows; it never recomposes them.+ */+private fun Modifier.rowHeight(sheetLayout: SheetLayout, r: Int, geo: State<Geo>): Modifier =+ layout { measurable, constraints ->+ val h = (sheetLayout.rowH(r) * geo.value.scale).roundToInt().coerceAtLeast(0)+ val p = measurable.measure(constraints.copy(minHeight = h, maxHeight = h))+ layout(p.width, h) { p.place(0, 0) }+ }++/** Lazily built row-number and column-letter strings. */+internal class GridLabels(nRows: Int, nCols: Int) {+ private val rows = arrayOfNulls<String>(nRows + 1)+ private val cols = arrayOfNulls<String>(nCols + 1)+ fun row(r: Int): String = rows.getOrNull(r)?: (r + 1).toString().also { if (r in rows.indices) rows[r] = it }+ fun col(c: Int): String = cols.getOrNull(c) ?: XlsxRefs.colLetter(c).also { if (c in cols.indices) cols[c] = it }+}++/** Geometry for one zoom level, captured so gesture handlers never see a stale layout. */internal class Geo(val layout: SheetLayout,val scale: Float,val frozenW: Float,+ /** Height of the frozen band as laid out: the sum of the rows' whole-pixel heights. */val frozenH: Float,val fc: Int,val gutterW: Float,- val headerH: Float-)+ val headerH: Float,+ private val frozenTops: FloatArray+) {+ /** Top of frozen row [r] (or the band's bottom for `r == frozenRows`), in laid-out pixels. */+ fun frozenTop(r: Int): Float = frozenTops[r.coerceIn(0, frozenTops.size - 1)]++ companion object {+ fun of(layout: SheetLayout, scale: Float, fc: Int, gutterW: Float, headerH: Float): Geo {+ val fr = layout.sheet.frozenRows.coerceAtMost(layout.nRows)+ val tops = FloatArray(fr + 1)+ for (r in 0 until fr) tops[r + 1] = tops[r] + (layout.rowH(r) * scale).roundToInt().coerceAtLeast(0)+ return Geo(layout, scale, layout.frozenWidth * scale, tops[fr], fc, gutterW, headerH, tops)+ }+ }+}private inline fun DrawScope.clipRect(left: Float, block: DrawScope.() -> Unit) {drawContext.canvas.save()@@ -494,7 +584,9 @@ private fun DrawScope.drawGridRow(scrollX: Float,colors: GridColors,headerPaint: Paint,+ headerTextDy: Float,bandPaint: Paint,+ labels: GridLabels,sel: GridSelection?,drawsMerge: (CellRange) -> Boolean) {@@ -509,17 +601,16 @@ private fun DrawScope.drawGridRow(// Sticky row-number gutter, drawn last so nothing paints over it.val inSel = sel != null && r in sel.range.r1..sel.range.r2- bandPaint.color = colors.headerBand.toArgb()+ bandPaint.color = colors.headerBandArgbnc.drawRect(0f, 0f, g.gutterW, h, bandPaint)if (inSel) {- bandPaint.color = colors.accent.copy(alpha = if (sel!!.isWholeRow) 0.30f else 0.14f).toArgb()+ bandPaint.color = if (sel!!.isWholeRow) colors.wholeSelBandArgb else colors.selBandArgbnc.drawRect(0f, 0f, g.gutterW, h, bandPaint)}- headerPaint.color = (if (inSel) colors.accent else colors.headerText).toArgb()+ headerPaint.color = if (inSel) colors.accentArgb else colors.headerTextArgbheaderPaint.isFakeBoldText = inSel- val fm = headerPaint.fontMetrics- if (h > headerPaint.textSize * 0.8f) nc.drawText((r + 1).toString(), g.gutterW / 2f, h / 2f - (fm.ascent + fm.descent) / 2f, headerPaint)- bandPaint.color = colors.headerDivider.toArgb()+ if (h > headerPaint.textSize * 0.8f) nc.drawText(labels.row(r), g.gutterW / 2f, h / 2f + headerTextDy, headerPaint)+ bandPaint.color = colors.headerDividerArgbnc.drawRect(g.gutterW - 1f, 0f, g.gutterW, h, bandPaint)nc.drawRect(g.gutterW * 0.25f, h - 1f, g.gutterW * 0.75f, h, bandPaint)}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetScrolling.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetScrolling.ktindex cb6a82d..d20e09c 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetScrolling.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetScrolling.kt@@ -3,16 +3,13 @@ package com.chethan616.clearpdf.ui.screenimport android.os.SystemClockimport android.view.HapticFeedbackConstantsimport androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.Spring-import androidx.compose.animation.core.animateDpAsStateimport androidx.compose.animation.core.animateFloatAsStateimport androidx.compose.animation.core.springimport androidx.compose.animation.core.tweenimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOut-import androidx.compose.animation.scaleIn-import androidx.compose.animation.scaleOut-import androidx.compose.foundation.backgroundimport androidx.compose.foundation.gestures.FlingBehaviorimport androidx.compose.foundation.gestures.ScrollScopeimport androidx.compose.foundation.gestures.ScrollableDefaults@@ -24,7 +21,6 @@ import androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.width-import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffect@@ -32,25 +28,34 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.runtime.snapshotFlowimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Sizeimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.lerpimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.platform.LocalViewimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.IntOffsetimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport com.chethan616.clearpdf.Rimport com.chethan616.clearpdf.ui.components.viewerGlassimport com.kyant.backdrop.backdrops.LayerBackdropimport com.kyant.shapes.Capsule+import kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.filter+import kotlinx.coroutines.launchimport kotlin.math.absimport kotlin.math.roundToInt@@ -88,32 +93,47 @@ internal fun SheetRowScrubber(if (rowCount < 60) returnval view = LocalView.current+ val scope = rememberCoroutineScope()var isDragging by remember { mutableStateOf(false) }var dragRow by remember { mutableIntStateOf(0) }val lastSpan = (rowCount - 1).coerceAtLeast(1)- // Follow normal (non-rail) scrolling when the rail itself isn't being touched.- LaunchedEffect(listState) {- snapshotFlow { listState.firstVisibleItemIndex }+ // The thumb's position, as a fraction of the track. Driven from a snapshotFlow into an+ // Animatable and read only in draw/layout lambdas below. Before, `firstVisibleItemIndex` was+ // copied into a state the scrubber read in composition and fed through `animateFloatAsState`+ // into a `padding(top = …)`: every row scrolled past recomposed and re-measured the scrubber,+ // and every frame of the follow-spring did it again — continuous recomposition for as long as+ // the sheet was moving.+ val thumb = remember { Animatable(0f) }+ LaunchedEffect(listState, lastSpan) {+ snapshotFlow { if (isDragging) dragRow else listState.firstVisibleItemIndex }.distinctUntilChanged()- .collect { idx -> if (!isDragging) dragRow = idx.coerceIn(0, lastSpan) }+ .collectLatest { idx ->+ thumb.animateTo(+ (idx.toFloat() / lastSpan).coerceIn(0f, 1f),+ spring(stiffness = Spring.StiffnessMediumLow, dampingRatio = Spring.DampingRatioNoBouncy)+ )+ }}// Haptic tick + live scroll on every row the drag crosses.- LaunchedEffect(dragRow, isDragging) {- if (isDragging) {- runCatching { view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) }- runCatching { listState.scrollToItem(dragRow) }- }+ LaunchedEffect(listState) {+ snapshotFlow { if (isDragging) dragRow else -1 }+ .filter { it >= 0 }+ .distinctUntilChanged()+ .collect { row ->+ runCatching { view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) }+ runCatching { listState.scrollToItem(row) }+ }}- val fraction by animateFloatAsState(- targetValue = (dragRow.toFloat() / lastSpan).coerceIn(0f, 1f),- animationSpec = spring(stiffness = Spring.StiffnessMediumLow, dampingRatio = Spring.DampingRatioNoBouncy),- label = "sheetScrubFraction"+ // 0 idle → 1 while dragging; widens the track and lengthens the thumb. A State read in draw.+ val active = animateFloatAsState(+ if (isDragging) 1f else 0f,+ spring(stiffness = Spring.StiffnessMedium),+ label = "sheetScrubActive")- val trackWidth by animateDpAsState(if (isDragging) 8.dp else 4.dp, spring(stiffness = Spring.StiffnessMedium), label = "sheetTrackWidth")- val thumbHeight by animateDpAsState(if (isDragging) 40.dp else 30.dp, spring(stiffness = Spring.StiffnessMedium), label = "sheetThumbHeight")+ val trackColor = if (isDark) Color.White.copy(0.14f) else Color.Black.copy(0.10f)Box(modifier) {Box(@@ -124,15 +144,17 @@ internal fun SheetRowScrubber(.pointerInput(rowCount) {detectTapGestures { offset ->val target = ((offset.y / size.height) * lastSpan).roundToInt().coerceIn(0, lastSpan)- dragRow = targetrunCatching { view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK) }+ // Tap-to-jump used to only move `dragRow`, which nothing scrolled to outside+ // a drag, so a tap on the rail did nothing.+ scope.launch { runCatching { listState.scrollToItem(target) } }}}.pointerInput(rowCount) {detectDragGestures(onDragStart = { start ->- isDragging = truedragRow = ((start.y / size.height) * lastSpan).roundToInt().coerceIn(0, lastSpan)+ isDragging = true},onDrag = { change, _ ->change.consume()@@ -141,27 +163,18 @@ internal fun SheetRowScrubber(onDragEnd = { isDragging = false },onDragCancel = { isDragging = false })- },- contentAlignment = Alignment.Center- ) {- Box(- Modifier- .width(trackWidth)- .height(SheetScrubberTrackHeight)- .clip(RoundedCornerShape(50))- .background(if (isDark) Color.White.copy(0.14f) else Color.Black.copy(0.10f)),- contentAlignment = Alignment.TopCenter- ) {- Box(- Modifier- .padding(top = ((SheetScrubberTrackHeight - thumbHeight) * fraction).coerceAtLeast(0.dp))- .width(if (isDragging) 8.dp else 4.dp)- .height(thumbHeight)- .clip(RoundedCornerShape(50))- .background(if (isDragging) accent else accent.copy(0.55f))- )- }- }+ }+ .drawBehind {+ val p = active.value+ val trackW = (4.dp + 4.dp * p).toPx()+ val thumbH = (30.dp + 10.dp * p).toPx()+ val x = (size.width - trackW) / 2f+ val radius = CornerRadius(trackW / 2f)+ drawRoundRect(trackColor, Offset(x, 0f), Size(trackW, size.height), radius)+ val y = (size.height - thumbH) * thumb.value+ drawRoundRect(lerp(accent.copy(alpha = 0.55f), accent, p), Offset(x, y), Size(trackW, thumbH), radius)+ }+ )// A small pill badge — "12/940", not "Row 12 / 940" in a wide card. Sized to match the 40 dp// search-icon circle it sits beside: a plain `CircleShape` can't hold a 4-digit fraction@@ -169,14 +182,18 @@ internal fun SheetRowScrubber(// as the digits actually need, via `defaultMinSize` rather than a fixed wide padding.AnimatedVisibility(visible = isDragging,- enter = fadeIn(tween(140)) + scaleIn(initialScale = 0.9f, animationSpec = tween(160)),- exit = fadeOut(tween(180)) + scaleOut(targetScale = 0.92f),+ enter = fadeIn(tween(140)),+ exit = fadeOut(tween(180)),modifier = Modifier.align(Alignment.CenterEnd)) {- val yOffset = (SheetScrubberTrackHeight * fraction - SheetScrubberTrackHeight / 2f).coerceIn(-90.dp, 90.dp)Box(Modifier- .offset(x = (-32).dp, y = yOffset)+ // Follows the thumb in the layout phase only; no recomposition per frame.+ .offset {+ val track = SheetScrubberTrackHeight.toPx()+ val y = (track * thumb.value - track / 2f).coerceIn(-90.dp.toPx(), 90.dp.toPx())+ IntOffset((-32).dp.roundToPx(), y.roundToInt())+ }.defaultMinSize(minWidth = 26.dp, minHeight = 26.dp).viewerGlass(backdrop, chromeGlass, shape = { Capsule }).padding(horizontal = 7.dp, vertical = 4.dp),diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt b/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.ktindex aa19b0b..c31a77f 100644--- a/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt+++ b/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt@@ -37,6 +37,12 @@ internal object ExcelCellFormat {48 to "##0.0E+0", 49 to "@")+ // Compiled once. These were built inside `apply`/`isDateCode`/`colorFor` — a fresh regex compile+ // for every cell formatted, and the grid formats every cell it draws.+ /** `[Red]`, `[$-409]`, `[<=100]` … but not the elapsed-time `[h]` / `[hh]` tokens. */+ private val BracketSection = Regex("\\[(?!h+]|hh+])[^]]*]", RegexOption.IGNORE_CASE)+ private val ColorSection = Regex("\\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\\s*(\\d+))]", RegexOption.IGNORE_CASE)+/** `numFmtId` 14 is "short date" in the *user's* locale, so it gets the device's pattern. */private val ShortDatePattern: String by lazy {runCatching {@@ -66,7 +72,7 @@ internal object ExcelCellFormat {/** True when [code] renders serials as dates/times. */fun isDateCode(code: String?): Boolean {if (code.isNullOrBlank() || code.equals("General", true)) return false- val body = splitSections(code).firstOrNull()?.replace(Regex("\\[(?!h+]|hh+])[^]]*]", RegexOption.IGNORE_CASE), "") ?: return false+ val body = splitSections(code).firstOrNull()?.replace(BracketSection, "") ?: return falsereturn runCatching { isDateTime(body) }.getOrDefault(false)}@@ -83,8 +89,7 @@ internal object ExcelCellFormat {value == 0.0 && sections.size >= 3 -> sections[2]else -> sections[0]}- val m = Regex("\\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\\s*(\\d+))]", RegexOption.IGNORE_CASE)- .find(section) ?: return null+ val m = ColorSection.find(section) ?: return nullreturn when (m.groupValues[1].lowercase().replace(" ", "").takeWhile { it.isLetter() }) {"black" -> 0xFF000000.toInt()"blue" -> 0xFF0000FF.toInt()@@ -118,7 +123,7 @@ internal object ExcelCellFormat {value == 0.0 && sections.size >= 3 -> sections[2]else -> sections[0]}- val body = section.replace(Regex("\\[(?!h+]|hh+])[^]]*]", RegexOption.IGNORE_CASE), "")+ val body = section.replace(BracketSection, "")if (body.isBlank()) return rawreturn runCatching {diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxPainter.kt b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxPainter.ktindex 230b0ec..62dc0f3 100644--- a/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxPainter.kt+++ b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxPainter.kt@@ -28,11 +28,36 @@ class SheetLayout(val sheet: XlsxSheet, extraRows: Int = 40, extraCols: Int = 8)val rowY = FloatArray(nRows + 1)/** Rows the scrolling list shows (not frozen, not hidden), in order. */val scrollRows: IntArray+ /**+ * Each column's default `xf` (its `<col style>`), so an empty cell's fill is an array read on+ * the draw path instead of a boxed `TreeMap` lookup per cell per frame.+ */+ val colStyle = IntArray(nCols)+ /**+ * The merges crossing each row. Before, every row draw filtered the sheet's whole merge list —+ * per row, per frame of a horizontal pan — which on a heavily merged report was the single+ * largest cost in the grid.+ */+ private val rowMerges: Array<List<CellRange>?> = arrayOfNulls(nRows)init {for (c in 0 until nCols) colX[c + 1] = colX[c] + colWidthPx(sheet.colWidthChars(c))for (r in 0 until nRows) rowY[r + 1] = rowY[r] + sheet.rowHeightPt(r) * 4f / 3f- scrollRows = (sheet.frozenRows until nRows).filter { !sheet.isRowHidden(it) }.toIntArray()+ // An IntArray filled in place: the old `(a until b).filter { }.toIntArray()` boxed every row+ // index of a 20 000-row sheet on the main thread each time the layout was rebuilt (every edit).+ val rows = IntArray((nRows - sheet.frozenRows).coerceAtLeast(0))+ var n = 0+ for (r in sheet.frozenRows until nRows) if (!sheet.isRowHidden(r)) rows[n++] = r+ scrollRows = if (n == rows.size) rows else rows.copyOf(n)+ for ((c, info) in sheet.cols) if (c in 0 until nCols && info.style >= 0) colStyle[c] = info.style+ for (m in sheet.merges) {+ val last = minOf(m.r2, nRows - 1)+ for (r in maxOf(m.r1, 0)..last) {+ @Suppress("UNCHECKED_CAST")+ val list = (rowMerges[r] as ArrayList<CellRange>?) ?: ArrayList<CellRange>(2).also { rowMerges[r] = it }+ list.add(m)+ }+ }}fun colW(c: Int) = colX[c + 1] - colX[c]@@ -41,6 +66,9 @@ class SheetLayout(val sheet: XlsxSheet, extraRows: Int = 40, extraCols: Int = 8)val frozenWidth get() = colX[sheet.frozenCols.coerceAtMost(nCols)]val frozenHeight get() = rowY[sheet.frozenRows.coerceAtMost(nRows)]+ /** Merges that cross row [r]; empty for almost every row. */+ fun mergesAt(r: Int): List<CellRange> = rowMerges.getOrNull(r) ?: emptyList()+/** Column at Excel-px x (clamped), skipping zero-width columns to the right. */fun colAt(x: Float): Int {var lo = 0@@ -90,36 +118,85 @@ class PaintTheme(/*** Paints cells with `android.graphics` — shared by the on-screen grid (one draw call per row, no* per-cell composables) and the PDF export, so the two can never disagree about how a cell looks.+ *+ * **Why everything about a cell is cached in [CellInfo].** A horizontal pan redraws every visible+ * row on every frame, so this runs for ~500 cells per frame. It used to re-derive each cell's facts+ * on each of those frames: `raw.toDoubleOrNull()` (a regex screen in the Kotlin stdlib) up to three+ * times per cell, `ExcelCellFormat.colorFor` (which compiles a `Regex` whenever the code has a+ * `[...]` section), a lower-cased copy of the font name, a fresh `FontMetrics`, and two+ * `measureText` calls. None of that can change while the cell doesn't — a [CellData] is immutable,+ * the style table only ever appends and the theme is fixed per painter — so it is computed once per+ * cell, keyed by identity. An edit replaces the edited cell's [CellData] instance, which is a cache+ * miss by construction, so nothing has to be cleared after an edit either (clearing used to+ * re-format and re-measure every visible cell on the frame after each commit).*/class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {private val fillPaint = Paint().apply { style = Paint.Style.FILL }private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }private val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)+ private val fm = Paint.FontMetrics()private val dash = DashPathEffect(floatArrayOf(4f, 3f), 0f)private val typefaces = HashMap<Int, Typeface>()- private val displayCache = java.util.IdentityHashMap<CellData, String>()+ /** Everything the draw path needs about one cell, derived once. */+ private class CellInfo(+ val text: String,+ val style: ResolvedStyle,+ val numeric: Boolean,+ /** Effective horizontal alignment ("general" resolved by value type). */+ val align: String,+ val ink: Int,+ val rich: RichText?,+ val multiline: Boolean,+ /** A date-formatted number: shows `####` when it doesn't fit, like Excel. */+ val isDate: Boolean,+ val typeface: Typeface+ ) {+ /** Text size [measuredWidth] was taken at; a zoom change is the only thing that moves it. */+ var measuredAt = -1f+ var measuredWidth = 0f+ }++ private val infoCache = java.util.IdentityHashMap<CellData, CellInfo>()private val layoutCache = object : LinkedHashMap<LayoutKey, StaticLayout>(64, 0.75f, true) {override fun removeEldestEntry(eldest: MutableMap.MutableEntry<LayoutKey, StaticLayout>?) = size > 300}private data class LayoutKey(val cell: CellData, val width: Int, val scale: Float, val wrap: Boolean)- fun invalidate() { displayCache.clear(); layoutCache.clear() }+ fun invalidate() { infoCache.clear(); layoutCache.clear() }- fun display(cell: CellData): String {- displayCache[cell]?.let { return it }- if (displayCache.size > 30_000) displayCache.clear()- return wb.display(cell).also { displayCache[cell] = it }- }+ /** What [cell] shows. Main thread only — the cache is not synchronised. */+ fun display(cell: CellData): String = info(cell).text- private fun styleOf(sheet: XlsxSheet, r: Int, c: Int, cell: CellData?): ResolvedStyle {- val s = when {- cell != null -> cell.style- else -> sheet.rows[r]?.style?.takeIf { it >= 0 } ?: sheet.cols[c]?.style?.takeIf { it >= 0 } ?: 0+ private fun info(cell: CellData): CellInfo {+ infoCache[cell]?.let { return it }+ if (infoCache.size > 40_000) infoCache.clear()+ val st = wb.styles.resolve(cell.style)+ val text = wb.display(cell)+ val numeric = cell.type == "" && cell.raw.isNotEmpty() && cell.raw.toDoubleOrNull() != null+ val align = when (st.hAlign) {+ "general" -> when {+ cell.type == "b" || cell.type == "e" -> "center"+ numeric -> "right"+ else -> "left"+ }+ "centerContinuous", "distributed" -> "center"+ "fill", "justify" -> "left"+ else -> st.hAlign}- return wb.styles.resolve(s)+ return CellInfo(+ text = text,+ style = st,+ numeric = numeric,+ align = align,+ ink = inkFor(st, st.fillArgb, cell),+ rich = wb.textOf(cell)?.takeIf { it.isRich },+ multiline = text.indexOf('\n') >= 0,+ isDate = numeric && ExcelCellFormat.isDateCode(st.numFmtCode),+ typeface = typeface(st)+ ).also { infoCache[cell] = it }}private fun typeface(st: ResolvedStyle): Typeface {@@ -139,7 +216,7 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {}/** Ink for a cell: explicit colour, number-format colour, or the theme's, kept legible. */- private fun inkFor(st: ResolvedStyle, fill: Int?, cell: CellData?, text: String): Int {+ private fun inkFor(st: ResolvedStyle, fill: Int?, cell: CellData?): Int {val fmtColor = if (cell != null && cell.type == "") ExcelCellFormat.colorFor(cell.raw, st.numFmtCode) else nullval explicit = fmtColor ?: st.fontArgbval bg = fill ?: theme.surface@@ -153,21 +230,6 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {return explicit}- private fun isNumeric(cell: CellData?): Boolean =- cell != null && cell.type == "" && cell.raw.isNotEmpty() && cell.raw.toDoubleOrNull() != null-- private fun effectiveH(st: ResolvedStyle, cell: CellData?): String = when (st.hAlign) {- "general" -> when {- cell == null -> "left"- cell.type == "b" || cell.type == "e" -> "center"- isNumeric(cell) -> "right"- else -> "left"- }- "centerContinuous", "distributed" -> "center"- "fill", "justify" -> "left"- else -> st.hAlign- }-/*** Draw one row. The canvas origin is the top-left of the cell area (right of the row gutter),* in screen pixels; [scale] is screen px per Excel px; [scrollX] is the horizontal scroll of the@@ -191,7 +253,7 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {if (h <= 0f) returnval frozenW = if (freeze) layout.frozenWidth * scale else 0fval fc = if (freeze) sheet.frozenCols.coerceAtMost(layout.nCols) else 0- val rowMerges = if (sheet.merges.isEmpty()) emptyList() else sheet.merges.filter { r in it.r1..it.r2 }+ val rowMerges = layout.mergesAt(r)// Scrolled region first, then the frozen columns on top of it.drawRegion(canvas, layout, r, h, scale, rowMerges, drawsMerge,@@ -204,6 +266,12 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {}}+ private fun inMerge(rowMerges: List<CellRange>, r: Int, c: Int): Boolean {+ if (rowMerges.isEmpty()) return false+ for (i in rowMerges.indices) if (rowMerges[i].contains(r, c)) return true+ return false+ }+private fun drawRegion(canvas: Canvas, layout: SheetLayout, r: Int, h: Float, scale: Float,rowMerges: List<CellRange>, drawsMerge: (CellRange) -> Boolean,@@ -212,6 +280,8 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {if (clipR <= clipL || lastCol < firstCol) returnval sheet = layout.sheetval row = sheet.rows[r]+ val cells = row?.cells?.takeIf { it.isNotEmpty() }+ val rowStyle = row?.style?.takeIf { it >= 0 }val c0 = maxOf(firstCol, layout.colAt((clipL - originX) / scale))var c1 = c0while (c1 < lastCol && originX + layout.colX[c1 + 1] * scale < clipR) c1++@@ -219,76 +289,78 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {canvas.clipRect(clipL, -100000f, clipR, h + 100000f)// Pass 1: fills + grid lines.+ linePaint.color = theme.gridLine; linePaint.strokeWidth = 1f; linePaint.pathEffect = nullfor (c in c0..c1) {val w = layout.colW(c) * scaleif (w <= 0f) continue- if (rowMerges.isNotEmpty() && rowMerges.any { it.contains(r, c) }) continue+ if (inMerge(rowMerges, r, c)) continueval x = originX + layout.colX[c] * scale- val cell = row?.cells?.get(c)- val st = styleOf(sheet, r, c, cell)- val fill = st.fillArgb+ val cell = cells?.get(c)+ val fill = if (cell != null) info(cell).style.fillArgb+ else wb.styles.resolve(rowStyle ?: layout.colStyle[c]).fillArgbif (fill != null) {fillPaint.color = fillcanvas.drawRect(x, 0f, x + w, h, fillPaint)} else if (sheet.showGridLines) {- linePaint.color = theme.gridLine; linePaint.strokeWidth = 1f; linePaint.pathEffect = nullcanvas.drawLine(x + w - 0.5f, 0f, x + w - 0.5f, h, linePaint)canvas.drawLine(x, h - 0.5f, x + w, h - 0.5f, linePaint)}}- // Pass 2: borders.- for (c in c0..c1) {- if (rowMerges.isNotEmpty() && rowMerges.any { it.contains(r, c) }) continue- val w = layout.colW(c) * scale- if (w <= 0f) continue- val cell = row?.cells?.get(c) ?: continue- val st = wb.styles.resolve(cell.style)- drawBorders(canvas, st, originX + layout.colX[c] * scale, 0f, w, h, scale)- }- // Pass 3: text, with overflow into empty neighbours.- if (row != null) {- val lo = maxOf(firstCol, row.cells.floorKey(c0)?.let { maxOf(it, c0 - 12) } ?: c0)- for ((c, cell) in row.cells.subMap(lo, true, minOf(lastCol, c1 + 12), true)) {- if (rowMerges.isNotEmpty() && rowMerges.any { it.contains(r, c) }) continue+ if (cells != null) {+ // Pass 2: borders.+ for ((c, cell) in cells.subMap(c0, true, c1, true)) {+ if (inMerge(rowMerges, r, c)) continueval w = layout.colW(c) * scaleif (w <= 0f) continue- val text = display(cell)- if (text.isEmpty()) continue- val st = wb.styles.resolve(cell.style)+ drawBorders(canvas, info(cell).style, originX + layout.colX[c] * scale, 0f, w, h, scale)+ }+ // Pass 3: text, with overflow into empty neighbours.+ val lo = maxOf(firstCol, cells.floorKey(c0)?.let { maxOf(it, c0 - 12) } ?: c0)+ for ((c, cell) in cells.subMap(lo, true, minOf(lastCol, c1 + 12), true)) {+ if (inMerge(rowMerges, r, c)) continue+ val w = layout.colW(c) * scale+ if (w <= 0f) continue+ val ci = info(cell)+ if (ci.text.isEmpty()) continue+ val st = ci.stylevar left = originX + layout.colX[c] * scalevar right = left + wval cellLeft = leftval cellRight = right- val align = effectiveH(st, cell)- if (!st.wrap && !isNumeric(cell) && cell.type != "b") {+ val align = ci.align+ if (!st.wrap && !ci.numeric && cell.type != "b") {// Excel spills unwrapped text into empty neighbours on the side it grows toward.if (align == "left" || align == "center") {var n = c + 1- while (n <= lastCol && n - c < 24 && row.cells[n]?.let { display(it).isEmpty() } != false &&- (rowMerges.isEmpty() || rowMerges.none { it.contains(r, n) })) {+ while (n <= lastCol && n - c < 24 && cells[n]?.let { info(it).text.isEmpty() } != false &&+ !inMerge(rowMerges, r, n)) {right += layout.colW(n) * scale; n++}}if (align == "right" || align == "center") {var n = c - 1- while (n >= firstCol && c - n < 24 && row.cells[n]?.let { display(it).isEmpty() } != false &&- (rowMerges.isEmpty() || rowMerges.none { it.contains(r, n) })) {+ while (n >= firstCol && c - n < 24 && cells[n]?.let { info(it).text.isEmpty() } != false &&+ !inMerge(rowMerges, r, n)) {left -= layout.colW(n) * scale; n--}}}- drawText(canvas, cell, st, text, cellLeft, cellRight, left, right, 0f, h, scale, st.fillArgb)+ drawText(canvas, cell, ci, cellLeft, cellRight, left, right, 0f, h, scale)}}// Pass 4: merges this row is responsible for.- for (m in rowMerges) {+ for (i in rowMerges.indices) {+ val m = rowMerges[i]if (m.c2 < c0 || m.c1 > c1 || !drawsMerge(m)) continueval x0 = originX + layout.colX[m.c1] * scaleval x1 = originX + layout.colX[(m.c2 + 1).coerceAtMost(layout.nCols)] * scaleval y0 = (layout.rowY[m.r1] - layout.rowY[r]) * scaleval y1 = (layout.rowY[(m.r2 + 1).coerceAtMost(layout.nRows)] - layout.rowY[r]) * scaleval cell = sheet.cell(m.r1, m.c1)- val st = styleOf(sheet, m.r1, m.c1, cell)+ val ci = cell?.let { info(it) }+ val st = ci?.style ?: wb.styles.resolve(+ sheet.rows[m.r1]?.style?.takeIf { it >= 0 } ?: layout.colStyle.getOrElse(m.c1) { 0 }+ )fillPaint.color = st.fillArgb ?: theme.surfacecanvas.drawRect(x0, y0, x1, y1, fillPaint)if (st.fillArgb == null && sheet.showGridLines) {@@ -302,15 +374,15 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {drawEdge(canvas, tl.top, x0, y0, x1, y0, scale)drawEdge(canvas, br.right ?: tl.right, x1, y0, x1, y1, scale)drawEdge(canvas, br.bottom ?: tl.bottom, x0, y1, x1, y1, scale)- if (cell != null) {- val text = display(cell)- if (text.isNotEmpty()) drawText(canvas, cell, st, text, x0, x1, x0, x1, y0, y1, scale, st.fillArgb)+ if (cell != null && ci != null && ci.text.isNotEmpty()) {+ drawText(canvas, cell, ci, x0, x1, x0, x1, y0, y1, scale)}}canvas.restore()}private fun drawBorders(canvas: Canvas, st: ResolvedStyle, x: Float, y: Float, w: Float, h: Float, scale: Float) {+ if (st.left == null && st.right == null && st.top == null && st.bottom == null) returndrawEdge(canvas, st.left, x, y, x, y + h, scale)drawEdge(canvas, st.right, x + w, y, x + w, y + h, scale)drawEdge(canvas, st.top, x, y, x + w, y, scale)@@ -341,32 +413,32 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {linePaint.pathEffect = null}- private fun configurePaint(st: ResolvedStyle, scale: Float, ink: Int) {- textPaint.typeface = typeface(st)+ private fun configurePaint(ci: CellInfo, scale: Float) {+ val st = ci.style+ textPaint.typeface = ci.typefacetextPaint.textSize = (st.sizePt * 4f / 3f * scale).coerceAtLeast(1f)- textPaint.color = ink+ textPaint.color = ci.inktextPaint.isUnderlineText = st.underlinetextPaint.isStrikeThruText = st.striketextPaint.isFakeBoldText = false}private fun drawText(- canvas: Canvas, cell: CellData, st: ResolvedStyle, text: String,+ canvas: Canvas, cell: CellData, ci: CellInfo,cellLeft: Float, cellRight: Float, spanLeft: Float, spanRight: Float,- top: Float, bottom: Float, scale: Float, fill: Int?+ top: Float, bottom: Float, scale: Float) {- val ink = inkFor(st, fill, cell, text)- configurePaint(st, scale, ink)+ val st = ci.style+ configurePaint(ci, scale)val pad = 3f * scaleval indent = st.indent * 9f * scale- val align = effectiveH(st, cell)- val rich = wb.textOf(cell)?.takeIf { it.isRich }+ val align = ci.alignval cellW = cellRight - cellLeftcanvas.save()canvas.clipRect(spanLeft, top, spanRight, bottom)- if (st.wrap || rich != null || text.contains('\n')) {+ if (st.wrap || ci.rich != null || ci.multiline) {val avail = if (st.wrap) (cellW - 2 * pad - indent).toInt().coerceAtLeast(1) else 100_000- val layout = staticLayout(cell, st, text, rich, avail, scale, ink, align)+ val layout = staticLayout(cell, ci, avail, scale, align)val lw = if (st.wrap) avail.toFloat() else (0 until layout.lineCount).maxOfOrNull { layout.getLineWidth(it) } ?: 0fval x = when (align) {"right" -> if (st.wrap) cellLeft + pad else cellRight - pad - lw - indent@@ -382,20 +454,24 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {canvas.translate(x, y)layout.draw(canvas)} else {- val fm = textPaint.fontMetrics+ textPaint.getFontMetrics(fm)val textH = fm.descent - fm.ascentval baseline = when (st.vAlign) {"top" -> top + pad / 2 - fm.ascent"center", "justify", "distributed" -> (top + bottom - textH) / 2f - fm.ascentelse -> bottom - pad / 2 - fm.descent}- var shown = text- val tw = textPaint.measureText(shown)- if (isNumeric(cell) && tw > cellW - 2 * pad && ExcelCellFormat.isDateCode(st.numFmtCode)) {+ var shown = ci.text+ if (ci.measuredAt != textPaint.textSize) {+ ci.measuredWidth = textPaint.measureText(shown)+ ci.measuredAt = textPaint.textSize+ }+ var w2 = ci.measuredWidth+ if (ci.isDate && w2 > cellW - 2 * pad) {// A date that doesn't fit shows ##### in Excel.shown = "#".repeat(((cellW - 2 * pad) / textPaint.measureText("#")).toInt().coerceAtLeast(1))+ w2 = textPaint.measureText(shown)}- val w2 = textPaint.measureText(shown)val x = when (align) {"right" -> spanRight.coerceAtMost(cellRight) - pad - w2 - indent"center" -> (cellLeft + cellRight - w2) / 2f@@ -412,11 +488,12 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {canvas.restore()}- private fun staticLayout(- cell: CellData, st: ResolvedStyle, text: String, rich: RichText?, width: Int, scale: Float, ink: Int, align: String- ): StaticLayout {+ private fun staticLayout(cell: CellData, ci: CellInfo, width: Int, scale: Float, align: String): StaticLayout {+ val st = ci.styleval key = LayoutKey(cell, width, scale, st.wrap)layoutCache[key]?.let { return it }+ val text = ci.text+ val rich = ci.richval tp = TextPaint(textPaint)val cs: CharSequence = if (rich?.runs == null) text else SpannableString(text).also { sp ->for (run in rich.runs) {@@ -430,7 +507,7 @@ class XlsxPainter(private val wb: XlsxWorkbook, val theme: PaintTheme) {if (f.underline) sp.setSpan(UnderlineSpan(), s, e, flags)if (f.strike) sp.setSpan(StrikethroughSpan(), s, e, flags)f.argb?.let { c ->- val legible = if (theme.isDark && st.fillArgb == null && XlsxColors.luminance(c) < 0.3) ink else c+ val legible = if (theme.isDark && st.fillArgb == null && XlsxColors.luminance(c) < 0.3) ci.ink else csp.setSpan(ForegroundColorSpan(legible), s, e, flags)}if (run.props.child("sz") != null) sp.setSpan(AbsoluteSizeSpan((f.size * 4f / 3f * scale).toInt().coerceAtLeast(1)), s, e, flags)