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: editor view model, canvas grid, scrolling helpers, strings
Chethan616fdbfa5c7b9f5
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.ktnew file mode 100644index 0000000..4343e59--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetGrid.kt@@ -0,0 +1,519 @@+package com.chethan616.clearpdf.ui.screen++import android.graphics.Paint+import android.graphics.Typeface+import androidx.compose.foundation.gestures.Orientation+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateZoom+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.rememberScrollableState+import androidx.compose.foundation.gestures.scrollable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.MutableFloatState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas+import androidx.compose.ui.graphics.nativeCanvas+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInRoot+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.dp+import com.chethan616.clearpdf.utils.xlsx.CellRange+import com.chethan616.clearpdf.utils.xlsx.SheetLayout+import com.chethan616.clearpdf.utils.xlsx.ValidationKind+import com.chethan616.clearpdf.utils.xlsx.XlsxPainter+import com.chethan616.clearpdf.utils.xlsx.XlsxRefs+import com.chethan616.clearpdf.utils.xlsx.XlsxSheet+import kotlin.math.abs++/** The selected range plus the cell typing goes into. */+data class GridSelection(val anchorR: Int, val anchorC: Int, val range: CellRange) {+ val isWholeColumn get() = range.r1 == 0 && range.r2 == XlsxRefs.MaxRow+ val isWholeRow get() = range.c1 == 0 && range.c2 == XlsxRefs.MaxCol++ companion object {+ fun cell(r: Int, c: Int, sheet: XlsxSheet): GridSelection =+ GridSelection(r, c, sheet.mergeAt(r, c) ?: CellRange(r, c, r, c))+ }+}++/** Colours for the grid chrome (headers, selection), derived from the app theme. */+class GridColors(+ val surface: Color,+ val headerBand: Color,+ val headerText: Color,+ val headerDivider: Color,+ val accent: Color+)++/**+ * The spreadsheet grid.+ *+ * Every row is a single draw call into [XlsxPainter] — no per-cell composables — inside a+ * `LazyColumn` so vertical scrolling keeps the stacking fling and the row scrubber. Horizontal+ * 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.+ */+@Composable+internal fun SpreadsheetGrid(+ sheet: XlsxSheet,+ layout: SheetLayout,+ painter: XlsxPainter,+ version: Int,+ zoom: Float,+ listState: LazyListState,+ scrollX: MutableFloatState,+ selection: GridSelection?,+ matches: List<Pair<Int, Int>>,+ currentMatch: Pair<Int, Int>?,+ colors: GridColors,+ editMode: Boolean,+ flingBehavior: androidx.compose.foundation.gestures.FlingBehavior,+ 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 * zoom+ val 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 * scale+ val fc = sheet.frozenCols.coerceAtMost(layout.nCols)+ val handleR = with(density) { 7.dp.toPx() }+ val chevronW = with(density) { 22.dp.toPx() }++ val currentSelection by rememberUpdatedState(selection)+ 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))++ var gridOrigin by remember { mutableStateOf(Offset.Zero) }+ /** Column being resized and its live width in Excel px. */+ var resize by remember { mutableStateOf<Pair<Int, Float>?>(null) }++ val headerPaint = remember(density.density) {+ Paint(Paint.ANTI_ALIAS_FLAG).apply {+ typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)+ textAlign = Paint.Align.CENTER+ textSize = with(density) { 12.dp.toPx() }+ }+ }+ val bandPaint = remember { Paint() }++ // 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)+ if (scrollX.floatValue > maxScroll) scrollX.floatValue = maxScroll+ val hState = rememberScrollableState { delta ->+ val old = scrollX.floatValue+ val next = (old - delta).coerceIn(0f, maxScroll)+ scrollX.floatValue = next+ old - 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+ val firstRow = g.layout.scrollRows.getOrNull(first.index) ?: return null+ val top = g.frozenH + first.offset + (g.layout.rowY[r.coerceAtMost(g.layout.nRows)] - g.layout.rowY[firstRow]) * g.scale+ val bottom = top + (g.layout.rowY[(r + 1).coerceAtMost(g.layout.nRows)] - g.layout.rowY[r.coerceAtMost(g.layout.nRows)]) * g.scale+ return top to bottom+ }++ fun colLeft(g: Geo, c: Int): Float {+ val cc = c.coerceIn(0, g.layout.nCols)+ return if (cc < g.fc) g.layout.colX[cc] * g.scale+ else g.frozenW + (g.layout.colX[cc] - g.layout.colX[g.fc]) * g.scale - scrollX.floatValue+ }++ /** 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 y = p.y - g.frozenH+ val item = listState.layoutInfo.visibleItemsInfo.firstOrNull { y >= it.offset && y < it.offset + it.size } ?: return null+ g.layout.scrollRows.getOrNull(item.index) ?: return null+ }+ val cx = p.x - g.gutterW+ if (cx < 0f) return r to -1+ val c = if (cx < g.frozenW) g.layout.colAt(cx / g.scale)+ else g.layout.colAt(g.layout.colX[g.fc] + (cx - g.frozenW + scrollX.floatValue) / g.scale)+ return r to c+ }++ fun selectionRect(g: Geo, s: GridSelection): Rect? {+ val r2 = s.range.r2.coerceAtMost(g.layout.nRows - 1)+ val c2 = s.range.c2.coerceAtMost(g.layout.nCols - 1)+ val top = rowRect(g, s.range.r1)?.first ?: return null+ val bottom = rowRect(g, r2)?.second ?: return null+ val left = g.gutterW + colLeft(g, s.range.c1)+ val right = g.gutterW + colLeft(g, c2 + 1)+ return Rect(left, top, right, bottom)+ }++ fun chevronRect(g: Geo, s: GridSelection): Rect? {+ if (!s.range.isSingle && sheet.mergeAt(s.anchorR, s.anchorC) != s.range) return null+ val v = sheet.validationAt(s.anchorR, s.anchorC) ?: return null+ if (v.kind != ValidationKind.LIST || v.showDropDown) return null+ val rect = selectionRect(g, s) ?: return null+ val h = minOf(rect.height, chevronW)+ return Rect(rect.right + 2f, rect.bottom - h, rect.right + 2f + chevronW, rect.bottom)+ }++ Column(+ modifier+ .fillMaxSize()+ .onGloballyPositioned { viewportW = it.size.width.toFloat(); gridOrigin = it.positionInRoot() }+ .scrollable(hState, Orientation.Horizontal)+ .pointerInput(Unit) {+ // Pinch to zoom; single-finger gestures pass through to scrolling.+ awaitEachGesture {+ awaitFirstDown(requireUnconsumed = false)+ do {+ val e = awaitPointerEvent()+ if (e.changes.count { it.pressed } >= 2) {+ val z = e.calculateZoom()+ if (z != 1f) { currentOnZoom(z); e.changes.forEach { it.consume() } }+ }+ } while (e.changes.any { it.pressed })+ }+ }+ ) {+ // ── Column header ──────────────────────────────────────────────────────+ Spacer(+ Modifier+ .fillMaxWidth()+ .height(28.dp)+ .pointerInput(Unit) {+ // Column resize: drag a header divider (edit mode).+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)+ if (!currentEdit) return@awaitEachGesture+ val g = geo.value+ val slop = 12.dp.toPx()+ var col = -1+ for (c in 0 until g.layout.nCols) {+ val edge = g.gutterW + colLeft(g, c + 1)+ if (edge > size.width + slop) break+ if (abs(down.position.x - edge) < slop && g.layout.colW(c) > 0f) { col = c; break }+ }+ if (col < 0) return@awaitEachGesture+ down.consume()+ var w = g.layout.colW(col)+ resize = col to w+ while (true) {+ val ev = awaitPointerEvent(PointerEventPass.Initial)+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (!ch.pressed) break+ w = (w + ch.positionChange().x / g.scale).coerceIn(12f, 1200f)+ resize = col to w+ ch.consume()+ }+ resize = null+ currentOnResize(col, SheetLayout.charsFromPx(w))+ }+ }+ .pointerInput(Unit) {+ detectTapGestures { p ->+ val g = geo.value+ val cx = p.x - g.gutterW+ if (cx < 0f) return@detectTapGestures+ val c = if (cx < g.frozenW) g.layout.colAt(cx / g.scale)+ else g.layout.colAt(g.layout.colX[g.fc] + (cx - g.frozenW + scrollX.floatValue) / g.scale)+ currentOnSelect(GridSelection(0, c, CellRange(0, c, XlsxRefs.MaxRow, c)))+ }+ }+ .drawBehind {+ val g = geo.value+ val sel = currentSelection+ drawRect(colors.headerBand)+ drawIntoCanvas { cv ->+ val nc = cv.nativeCanvas+ nc.save()+ nc.clipRect(g.gutterW, 0f, size.width, size.height)+ fun drawCol(c: Int) {+ val w = g.layout.colW(c) * g.scale+ if (w <= 0f) return+ val x = g.gutterW + colLeft(g, c)+ if (x > size.width || x + w < g.gutterW) return+ val inSel = sel != null && c in sel.range.c1..sel.range.c2+ if (inSel) {+ bandPaint.color = colors.accent.copy(alpha = if (sel!!.isWholeColumn) 0.30f else 0.14f).toArgb()+ nc.drawRect(x, 0f, x + w, size.height, bandPaint)+ }+ headerPaint.color = (if (inSel) colors.accent else colors.headerText).toArgb()+ headerPaint.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.drawRect(x + w - 1f, size.height * 0.22f, x + w, size.height * 0.78f, bandPaint)+ }+ // Scrolling columns, then frozen ones over them.+ val startC = g.layout.colAt(g.layout.colX[g.fc] + scrollX.floatValue / g.scale)+ var c = maxOf(g.fc, startC)+ nc.save()+ nc.clipRect(g.gutterW + g.frozenW, 0f, size.width, size.height)+ while (c < g.layout.nCols && g.gutterW + colLeft(g, c) < size.width) { drawCol(c); c++ }+ nc.restore()+ for (fcI in 0 until g.fc) drawCol(fcI)+ nc.restore()+ }+ drawLine(colors.headerDivider, Offset(0f, size.height - 0.5f), Offset(size.width, size.height - 0.5f), 1f)+ drawLine(colors.headerDivider, Offset(g.gutterW - 0.5f, 0f), Offset(g.gutterW - 0.5f, size.height), 1f)+ if (g.frozenW > 0f) drawLine(colors.headerDivider, Offset(g.gutterW + g.frozenW, 0f), Offset(g.gutterW + g.frozenW, size.height), 2f)+ resize?.let { (rc, w) ->+ val x = g.gutterW + colLeft(g, rc) + w * g.scale+ drawLine(colors.accent, Offset(x, 0f), Offset(x, size.height), 2.dp.toPx())+ }+ }+ )++ // ── Body ───────────────────────────────────────────────────────────────+ Box(+ Modifier+ .fillMaxWidth()+ .weight(1f)+ .clipToBounds()+ .pointerInput(Unit) {+ // Range handles: grabbed before the list sees the drag.+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)+ val sel = currentSelection ?: return@awaitEachGesture+ val g = geo.value+ val rect = selectionRect(g, sel) ?: return@awaitEachGesture+ val grab = handleR * 3.2f+ val tl = (down.position - rect.topLeft).getDistance() < grab+ val br = (down.position - rect.bottomRight).getDistance() < grab+ if (!tl && !br) return@awaitEachGesture+ down.consume()+ val fixedR = if (br) sel.range.r1 else sel.range.r2+ val fixedC = if (br) sel.range.c1 else sel.range.c2+ while (true) {+ val ev = awaitPointerEvent(PointerEventPass.Initial)+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (!ch.pressed) break+ ch.consume()+ val h = hit(g, ch.position) ?: continue+ val c = h.second.coerceAtLeast(0)+ var range = CellRange.of(fixedR, fixedC, h.first, c)+ // Grow to cover any merge the range cuts through.+ for (m in sheet.merges) if (m.r1 <= range.r2 && m.r2 >= range.r1 && m.c1 <= range.c2 && m.c2 >= range.c1) {+ range = CellRange(minOf(range.r1, m.r1), minOf(range.c1, m.c1), maxOf(range.r2, m.r2), maxOf(range.c2, m.c2))+ }+ currentOnSelect(sel.copy(range = range))+ }+ }+ }+ .pointerInput(Unit) {+ detectTapGestures { p ->+ val g = geo.value+ val sel = currentSelection+ if (sel != null) {+ chevronRect(g, sel)?.let { cr ->+ if (cr.inflate(8.dp.toPx()).contains(p)) {+ val rect = selectionRect(g, sel) ?: cr+ currentOnDropdown(sel.anchorR, sel.anchorC, rect.translate(gridOrigin + Offset(0f, g.headerH)))+ return@detectTapGestures+ }+ }+ }+ val (r, c) = hit(g, p) ?: return@detectTapGestures+ if (c < 0) {+ currentOnSelect(GridSelection(r, 0, CellRange(r, 0, r, XlsxRefs.MaxCol)))+ return@detectTapGestures+ }+ val next = GridSelection.cell(r, c, sheet)+ if (sel != null && sel.range == next.range && sel.anchorR == next.anchorR && sel.anchorC == next.anchorC) {+ currentOnTapSelected(next.anchorR, next.anchorC)+ } else currentOnSelect(next)+ }+ }+ ) {+ 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+ Spacer(+ Modifier.fillMaxWidth().height(with(density) { h.toDp() })+ .drawBehind { drawGridRow(r, painter, layout, geo.value, scrollX.floatValue, colors, headerPaint, bandPaint, currentSelection) { m -> m.r1 == r } }+ )+ }+ LazyColumn(+ Modifier.fillMaxWidth().weight(1f),+ state = listState,+ flingBehavior = flingBehavior+ ) {+ items(count = layout.scrollRows.size, key = { layout.scrollRows[it] }) { i ->+ val r = layout.scrollRows[i]+ val h = layout.rowH(r) * scale+ Spacer(+ Modifier.fillMaxWidth().height(with(density) { h.toDp() })+ .drawBehind {+ @Suppress("UNUSED_EXPRESSION") version+ drawGridRow(r, painter, layout, geo.value, scrollX.floatValue, colors, headerPaint, bandPaint, currentSelection) { m ->+ val firstRow = layout.scrollRows.getOrElse(listState.firstVisibleItemIndex) { 0 }+ r == maxOf(m.r1, firstRow, sheet.frozenRows)+ }+ }+ )+ }+ }+ }+ if (frozenH > 0f) {+ Spacer(Modifier.fillMaxSize().drawBehind {+ drawLine(colors.headerDivider, Offset(0f, frozenH), Offset(size.width, frozenH), 2f)+ })+ }+ if (frozenW > 0f) {+ Spacer(Modifier.fillMaxSize().drawBehind {+ drawLine(colors.headerDivider, Offset(gutterW + frozenW, 0f), Offset(gutterW + frozenW, size.height), 2f)+ })+ }++ // ── Overlay: search hits, selection, handles, dropdown chevron ───────+ Spacer(+ Modifier.fillMaxSize().drawBehind {+ val g = geo.value+ @Suppress("UNUSED_EXPRESSION") version+ clipRect(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)+ }+ }+ val sel = currentSelection ?: return@clipRect+ val rect = selectionRect(g, sel) ?: return@clipRect+ if (!sel.range.isSingle && sheet.mergeAt(sel.anchorR, sel.anchorC) != sel.range) {+ drawRect(colors.accent.copy(alpha = 0.10f), rect.topLeft, rect.size)+ }+ drawRect(colors.accent, rect.topLeft, rect.size, style = Stroke(2.dp.toPx()))+ if (currentEdit || !sel.range.isSingle) {+ for (pt in listOf(rect.topLeft, rect.bottomRight)) {+ drawCircle(Color.White, handleR + 1.5.dp.toPx(), pt)+ drawCircle(colors.accent, handleR, pt)+ }+ }+ chevronRect(g, sel)?.let { cr ->+ drawRoundRect(+ colors.surface, cr.topLeft, cr.size,+ androidx.compose.ui.geometry.CornerRadius(5.dp.toPx())+ )+ drawRoundRect(+ colors.headerDivider, cr.topLeft, cr.size,+ androidx.compose.ui.geometry.CornerRadius(5.dp.toPx()), style = Stroke(1f)+ )+ val cx = cr.center.x+ val cy = cr.center.y+ val s = 4.dp.toPx()+ val path = androidx.compose.ui.graphics.Path().apply {+ moveTo(cx - s, cy - s / 2); lineTo(cx, cy + s / 2); lineTo(cx + s, cy - s / 2)+ }+ drawPath(path, colors.accent, style = Stroke(1.8.dp.toPx(), cap = androidx.compose.ui.graphics.StrokeCap.Round, join = androidx.compose.ui.graphics.StrokeJoin.Round))+ }+ }+ resize?.let { (rc, w) ->+ val x = g.gutterW + colLeft(g, rc) + w * g.scale+ drawLine(colors.accent, Offset(x, 0f), Offset(x, size.height), 1.5.dp.toPx())+ }+ }+ )+ }+ }+}++/** Frozen geometry for one frame, captured so gesture handlers never see a stale layout. */+internal class Geo(+ val layout: SheetLayout,+ val scale: Float,+ val frozenW: Float,+ val frozenH: Float,+ val fc: Int,+ val gutterW: Float,+ val headerH: Float+)++private inline fun DrawScope.clipRect(left: Float, block: DrawScope.() -> Unit) {+ drawContext.canvas.save()+ drawContext.canvas.clipRect(left, 0f, size.width, size.height)+ block()+ drawContext.canvas.restore()+}++/** Gutter (row number) + the row's cells, via the shared painter. */+private fun DrawScope.drawGridRow(+ r: Int,+ painter: XlsxPainter,+ layout: SheetLayout,+ g: Geo,+ scrollX: Float,+ colors: GridColors,+ headerPaint: Paint,+ bandPaint: Paint,+ sel: GridSelection?,+ drawsMerge: (CellRange) -> Boolean+) {+ val h = size.height+ drawIntoCanvas { cv ->+ val nc = cv.nativeCanvas+ nc.save()+ nc.translate(g.gutterW, 0f)+ nc.clipRect(0f, -100_000f, size.width - g.gutterW, h + 100_000f)+ painter.drawRow(nc, layout, r, g.scale, scrollX, size.width - g.gutterW, drawsMerge = drawsMerge)+ nc.restore()++ // 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()+ nc.drawRect(0f, 0f, g.gutterW, h, bandPaint)+ if (inSel) {+ bandPaint.color = colors.accent.copy(alpha = if (sel!!.isWholeRow) 0.30f else 0.14f).toArgb()+ nc.drawRect(0f, 0f, g.gutterW, h, bandPaint)+ }+ headerPaint.color = (if (inSel) colors.accent else colors.headerText).toArgb()+ headerPaint.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()+ nc.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.ktnew file mode 100644index 0000000..cb6a82d--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetScrolling.kt@@ -0,0 +1,275 @@+package com.chethan616.clearpdf.ui.screen++import android.os.SystemClock+import android.view.HapticFeedbackConstants+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.scaleOut+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.FlingBehavior+import androidx.compose.foundation.gestures.ScrollScope+import androidx.compose.foundation.gestures.ScrollableDefaults+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.defaultMinSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicText+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.chethan616.clearpdf.R+import com.chethan616.clearpdf.ui.components.viewerGlass+import com.kyant.backdrop.backdrops.LayerBackdrop+import com.kyant.shapes.Capsule+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlin.math.abs+import kotlin.math.roundToInt++private val SheetScrubberTrackHeight = 208.dp++/**+ * A WPS/Excel-style vertical jump rail for the row axis — drag to scroll to any row in one motion,+ * with a small floating "N/Total" badge that tracks the finger, instead of counting flicks to get+ * from row 12 to row 940.+ *+ * Modelled directly on [PageScrubber] (the PDF viewer's page rail): same track/thumb sizing, same+ * tap-to-jump + drag-to-scrub gesture, same haptic tick per step. The one real difference is that a+ * spreadsheet has no per-row render cost the way a PDF page does, so this scrolls the list live on+ * every drag tick instead of only on release — the sheet content itself becomes the "preview",+ * which is what the WPS reference screenshot actually shows (the grid moving under the thumb, not a+ * separate popup).+ *+ * Only shown for sheets long enough that the rail is a shortcut rather than clutter — a 20-row sheet+ * scrolls in one swipe already.+ */+@Composable+internal fun SheetRowScrubber(+ listState: androidx.compose.foundation.lazy.LazyListState,+ rowCount: Int,+ backdrop: LayerBackdrop,+ chromeGlass: Color,+ accent: Color,+ text: Color,+ isDark: Boolean,+ modifier: Modifier = Modifier,+ /** Sheet row number (1-based) shown in the badge for list index `i`. */+ labelFor: (Int) -> Int = { it + 1 },+ totalLabel: Int = rowCount+) {+ if (rowCount < 60) return++ val view = LocalView.current+ 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 }+ .distinctUntilChanged()+ .collect { idx -> if (!isDragging) dragRow = idx.coerceIn(0, lastSpan) }+ }++ // 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) }+ }+ }++ val fraction by animateFloatAsState(+ targetValue = (dragRow.toFloat() / lastSpan).coerceIn(0f, 1f),+ animationSpec = spring(stiffness = Spring.StiffnessMediumLow, dampingRatio = Spring.DampingRatioNoBouncy),+ label = "sheetScrubFraction"+ )+ 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")++ Box(modifier) {+ Box(+ Modifier+ .align(Alignment.CenterEnd)+ .height(SheetScrubberTrackHeight)+ .width(28.dp)+ .pointerInput(rowCount) {+ detectTapGestures { offset ->+ val target = ((offset.y / size.height) * lastSpan).roundToInt().coerceIn(0, lastSpan)+ dragRow = target+ runCatching { view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK) }+ }+ }+ .pointerInput(rowCount) {+ detectDragGestures(+ onDragStart = { start ->+ isDragging = true+ dragRow = ((start.y / size.height) * lastSpan).roundToInt().coerceIn(0, lastSpan)+ },+ onDrag = { change, _ ->+ change.consume()+ dragRow = ((change.position.y / size.height) * lastSpan).roundToInt().coerceIn(0, lastSpan)+ },+ 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))+ )+ }+ }++ // 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+ // without clipping, so this starts as a near-circle for short numbers and only widens as far+ // 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),+ modifier = Modifier.align(Alignment.CenterEnd)+ ) {+ val yOffset = (SheetScrubberTrackHeight * fraction - SheetScrubberTrackHeight / 2f).coerceIn(-90.dp, 90.dp)+ Box(+ Modifier+ .offset(x = (-32).dp, y = yOffset)+ .defaultMinSize(minWidth = 26.dp, minHeight = 26.dp)+ .viewerGlass(backdrop, chromeGlass, shape = { Capsule })+ .padding(horizontal = 7.dp, vertical = 4.dp),+ contentAlignment = Alignment.Center+ ) {+ BasicText(+ stringResource(R.string.sheet_row_of, labelFor(dragRow), totalLabel),+ style = TextStyle(text, 10.sp, FontWeight.SemiBold),+ maxLines = 1+ )+ }+ }+ }+}++/**+ * A fling behaviour that stacks: flick fast in the same direction again before the previous fling+ * has settled and the next one travels further, up to [MaxFlingMultiplier] times a normal one.+ *+ * A spreadsheet is the one screen in this app that is routinely thousands of rows long, and the+ * platform fling is tuned for lists you read rather than lists you traverse — reaching row 4000+ * takes a tiring number of identical swipes. Repeated fast swipes are already the gesture people+ * reach for there, so this reads them as one intent and gives them distance.+ *+ * It boosts the *initial velocity* and then hands off to the platform's own decay curve, so the+ * motion is the standard one throughout — faster, never jumpier. Nothing snaps or teleports.+ *+ * Only deliberate flicks count toward a streak: a swipe under [MinStreakVelocityDp] per second is+ * someone positioning carefully, and stacking those would make precise scrolling impossible.+ * Changing direction, or pausing past [StreakWindowMillis], resets it.+ */+@Composable+internal fun rememberStackingFlingBehavior(): FlingBehavior {+ val base = ScrollableDefaults.flingBehavior()+ val minVelocity = with(LocalDensity.current) { MinStreakVelocityDp.dp.toPx() }+ return remember(base, minVelocity) { StackingFlingBehavior(base, minVelocity) }+}++/** dp per second below which a swipe is treated as positioning, not as a fast flick. */+private const val MinStreakVelocityDp = 1200f++/** How long after a fling a follow-up still counts as part of the same burst. */+private const val StreakWindowMillis = 320L++/** Each consecutive fast flick adds this much of a normal fling's velocity. */+private const val FlingBoostPerSwipe = 0.9f++/** Ceiling, so a long burst can't launch the sheet somewhere unrecoverable. */+private const val MaxFlingMultiplier = 4f++private class StackingFlingBehavior(+ private val base: FlingBehavior,+ private val minVelocity: Float+) : FlingBehavior {++ private var lastDirection = 0+ private var lastFlingAtMillis = 0L+ private var streak = 0++ override suspend fun ScrollScope.performFling(initialVelocity: Float): Float {+ val now = SystemClock.uptimeMillis()+ val direction = when {+ initialVelocity > 0f -> 1+ initialVelocity < 0f -> -1+ else -> 0+ }+ val isFastFlick = abs(initialVelocity) >= minVelocity+ val continuesBurst = direction != 0 &&+ direction == lastDirection &&+ now - lastFlingAtMillis <= StreakWindowMillis++ streak = if (isFastFlick && continuesBurst) streak + 1 else 0+ lastDirection = direction+ lastFlingAtMillis = now++ val multiplier = (1f + streak * FlingBoostPerSwipe).coerceAtMost(MaxFlingMultiplier)+ // Delegating rather than animating here is the point: the decay curve, the over-scroll+ // handover and the "velocity left over" contract all stay exactly the platform's.+ return with(base) { performFling(initialVelocity * multiplier) }+ }+}++/** Share the (mirrored) file. file:// → FileProvider content:// so it isn't exposed → no crash. */+internal fun shareFile(context: android.content.Context, uri: android.net.Uri) {+ val shareUri = if (uri.scheme == "file") {+ runCatching {+ androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.provider", java.io.File(uri.path!!))+ }.getOrNull() ?: uri+ } else uri+ val intent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {+ type = context.contentResolver.getType(shareUri) ?: "application/octet-stream"+ putExtra(android.content.Intent.EXTRA_STREAM, shareUri)+ addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ runCatching { context.startActivity(android.content.Intent.createChooser(intent, null)) }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.ktindex e474af0..9d97551 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/SpreadsheetViewModel.kt@@ -8,6 +8,20 @@ import com.chethan616.clearpdf.data.repository.LocalDocumentMirrorimport com.chethan616.clearpdf.data.repository.RecentFileimport com.chethan616.clearpdf.data.repository.RecentFilesManagerimport com.chethan616.clearpdf.utils.SpreadsheetParser+import com.chethan616.clearpdf.utils.xlsx.Axis+import com.chethan616.clearpdf.utils.xlsx.BorderSide+import com.chethan616.clearpdf.utils.xlsx.CellChange+import com.chethan616.clearpdf.utils.xlsx.CellData+import com.chethan616.clearpdf.utils.xlsx.CellRange+import com.chethan616.clearpdf.utils.xlsx.ColorSpec+import com.chethan616.clearpdf.utils.xlsx.EditOp+import com.chethan616.clearpdf.utils.xlsx.StylePatch+import com.chethan616.clearpdf.utils.xlsx.StyleTable+import com.chethan616.clearpdf.utils.xlsx.XlsxEdits+import com.chethan616.clearpdf.utils.xlsx.XlsxReader+import com.chethan616.clearpdf.utils.xlsx.XlsxSheet+import com.chethan616.clearpdf.utils.xlsx.XlsxWorkbook+import com.chethan616.clearpdf.utils.xlsx.XlsxWriterimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlow@@ -16,30 +30,47 @@ import kotlinx.coroutines.withContextimport java.io.Fileimport java.io.FileOutputStream-/** Loads a spreadsheet (.xlsx/.xls) into structured sheets for the interactive viewer. */+/** Border presets the toolbar offers, applied across a selected range. */+enum class BorderPreset { ALL, OUTER, INNER, TOP, BOTTOM, LEFT, RIGHT, THICK_OUTER, NONE }++/**+ * Loads a spreadsheet into an editable [XlsxWorkbook] and owns the edit log.+ *+ * Every change is an [EditOp] applied to the in-memory model; undo/redo move ops between the two+ * stacks; saving replays the applied stack onto the *pristine* local mirror of the file with+ * [XlsxWriter], so what gets written is exactly what is on screen and nothing else in the package+ * is touched.+ */class SpreadsheetViewModel : ViewModel() {data class UiState(val fileName: String = "",- val fileUri: Uri? = null, // local (mirrored) copy, for sharing- val sheets: List<SpreadsheetParser.Sheet> = emptyList(),+ /** Local mirror of the file as opened (never modified). */+ val fileUri: Uri? = null,+ /** The uri the user opened — the "Save" target. */+ val sourceUri: Uri? = null,+ val workbook: XlsxWorkbook? = null,val isLoading: Boolean = true,val error: String? = null,- /** True once any cell has been edited in this session. */- val isEdited: Boolean = false- )+ /** Bumped on every model change so the grid redraws. */+ val version: Int = 0,+ val canUndo: Boolean = false,+ val canRedo: Boolean = false,+ val dirty: Boolean = false,+ val saving: Boolean = false+ ) {+ val editable: Boolean get() = workbook?.editable == true && fileUri?.scheme == "file"+ }private val _state = MutableStateFlow(UiState())val state = _state.asStateFlow()private var started = false- /**- * Opening a spreadsheet must not be able to kill the app. Everything below runs inside- * `viewModelScope.launch`, where an escaping exception is uncaught and fatal — and three of the- * calls here talk to a `ContentProvider` the app does not own (`query`, `openInputStream`) or- * to shared preferences, any of which can throw on a URI whose grant has lapsed. Each step is- * therefore individually guarded and degrades to the on-screen error state instead.- */+ private val applied = ArrayList<EditOp>()+ private val redoStack = ArrayList<EditOp>()+ /** `applied.size` at the last save, or -1 when that state is no longer reachable by undo. */+ private var savedAt = 0+fun load(context: Context, uri: Uri) {if (started) returnstarted = true@@ -47,86 +78,287 @@ class SpreadsheetViewModel : ViewModel() {runCatching {context.contentResolver.takePersistableUriPermission(uri, android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)}+ runCatching {+ context.contentResolver.takePersistableUriPermission(uri, android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION)+ }val name = withContext(Dispatchers.IO) {runCatching { queryName(context, uri) }.getOrNull()?: RecentFilesManager.getRecents(context).firstOrNull { it.uriString == uri.toString() }?.name?: uri.lastPathSegment ?: "Spreadsheet"}- val (sheets, localUri) = withContext(Dispatchers.IO) {- // `uri` may be a share-intent grant on the way to being revoked — see- // `LocalDocumentMirror`'s doc comment for why that turns "opened once" into- // "Couldn't read this spreadsheet." the next time it's tapped from Recents.- // `readable` is `uri` itself when still good, or a durable local copy saved the- // first time it was.+ val (wb, localUri) = withContext(Dispatchers.IO) {val extension = name.substringAfterLast('.', "xlsx").lowercase()- val readable = LocalDocumentMirror.resolve(context, uri, extension)- // Mirror to app cache too, purely so the working copy for THIS session survives a- // revoked grant appearing mid-session (e.g. the sender's task finishes while the- // sheet is open) without touching `readable` again.+ val readable = runCatching { LocalDocumentMirror.resolve(context, uri, extension) }.getOrDefault(uri)val local = runCatching { mirrorToCache(context, readable, name) }.getOrDefault(readable)- SpreadsheetParser.parse(context, local) to local+ val book = runCatching {+ if (name.lowercase().endsWith(".xls")) fromLegacy(SpreadsheetParser.parse(context, local))+ else context.contentResolver.openInputStream(local)?.use { XlsxReader.read(it) }+ }.getOrNull()+ book to local}- _state.value = if (sheets.isEmpty()) {- UiState(fileName = name, fileUri = localUri, isLoading = false, error = "Couldn't read this spreadsheet.")+ val visible = wb?.sheets?.any { !it.hidden } == true+ _state.value = if (wb == null || !visible) {+ UiState(fileName = name, fileUri = localUri, sourceUri = uri, isLoading = false, error = "Couldn't read this spreadsheet.")} else {- UiState(fileName = name, fileUri = localUri, sheets = sheets, isLoading = false)+ UiState(fileName = name, fileUri = localUri, sourceUri = uri, workbook = wb, isLoading = false)}- if (sheets.isNotEmpty()) withContext(Dispatchers.IO) {- // The picked uri, not `localUri`. The mirror gets a fresh `System.currentTimeMillis()`- // filename on every open, so keying recents on it meant `addRecent` could never- // recognise a repeat and one spreadsheet accumulated a row per open. The mirror is a- // cache artifact; the document's identity is the uri the user chose. Re-opening from- // recents re-mirrors, which is what the mirror is for.+ if (wb != null) withContext(Dispatchers.IO) {runCatching {RecentFilesManager.addRecent(context,- RecentFile(- name = name,- uriString = uri.toString(),- timestamp = System.currentTimeMillis(),- pageCount = sheets.size- )+ RecentFile(name = name, uriString = uri.toString(), timestamp = System.currentTimeMillis(), pageCount = wb.sheets.count { !it.hidden }))}}}}+ /** Legacy .xls: values only, read-only (there is no package to patch). */+ private fun fromLegacy(sheets: List<SpreadsheetParser.Sheet>): XlsxWorkbook? {+ if (sheets.isEmpty()) return null+ val out = sheets.mapIndexed { i, s ->+ XlsxSheet(s.name, "legacy$i").also { xs ->+ s.rows.forEachIndexed { r, row ->+ val rowNo = s.rowNumberAt(r) - 1+ row.forEachIndexed { c, v ->+ if (v.isNotEmpty()) {+ val col = com.chethan616.clearpdf.utils.xlsx.XlsxRefs.colIndex(s.labelAt(c)).coerceAtLeast(0)+ xs.rows.getOrPut(rowNo) { com.chethan616.clearpdf.utils.xlsx.RowData() }.cells[col] =+ CellData(if (v.toDoubleOrNull() != null) "" else "inlineStr", v, 0)+ }+ }+ }+ }+ }+ return XlsxWorkbook(out, StyleTable.empty(), emptyList(), editable = false)+ }++ // ── edit log ───────────────────────────────────────────────────────────────++ private fun push(op: EditOp) {+ val wb = _state.value.workbook ?: return+ if (!wb.editable) return+ XlsxEdits.apply(wb, op)+ applied.add(op)+ redoStack.clear()+ if (savedAt > applied.size - 1) savedAt = -1+ // No cap: the writer replays this whole list onto the pristine file, so dropping the+ // oldest op would silently drop it from the saved workbook too.+ publish()+ }++ private fun publish() {+ _state.value = _state.value.copy(+ version = _state.value.version + 1,+ canUndo = applied.isNotEmpty(),+ canRedo = redoStack.isNotEmpty(),+ dirty = applied.size != savedAt+ )+ }++ fun undo() {+ val wb = _state.value.workbook ?: return+ val op = applied.removeLastOrNull() ?: return+ XlsxEdits.revert(wb, op)+ redoStack.add(op)+ publish()+ }++ fun redo() {+ val wb = _state.value.workbook ?: return+ val op = redoStack.removeLastOrNull() ?: return+ XlsxEdits.apply(wb, op)+ applied.add(op)+ publish()+ }++ /** Commit typed text into a cell; empty text clears the value but keeps its formatting. */+ fun setCellText(sheet: Int, r: Int, c: Int, text: String) {+ val wb = _state.value.workbook ?: return+ val s = wb.sheets.getOrNull(sheet) ?: return+ val before = s.cell(r, c)+ val style = before?.style ?: 0+ val after = if (text.isEmpty()) (if (style != 0) CellData("", "", style) else null) else wb.parseInput(text, style)+ if (before == after) return+ if (before != null && after != null && wb.editText(before) == text && before.style == after.style) return+ push(EditOp.SetCells(sheet, listOf(CellChange(r, c, before, after))))+ }++ fun clearRange(sheet: Int, range: CellRange) {+ val wb = _state.value.workbook ?: return+ val s = wb.sheets.getOrNull(sheet) ?: return+ val changes = cellsIn(s, range, existingOnly = true).mapNotNull { (r, c) ->+ val before = s.cell(r, c) ?: return@mapNotNull null+ if (before.isBlank) null+ else CellChange(r, c, before, if (before.style != 0) CellData("", "", before.style) else null)+ }+ if (changes.isNotEmpty()) push(EditOp.SetCells(sheet, changes))+ }++ fun applyStyle(sheet: Int, range: CellRange, patch: StylePatch) {+ applyStylePer(sheet, range) { _, _ -> patch }+ }++ fun applyBorders(sheet: Int, range: CellRange, preset: BorderPreset, color: ColorSpec? = null) {+ val thin = BorderSide("thin", color)+ val thick = BorderSide("medium", color)+ val none = BorderSide(null)+ applyStylePer(sheet, range) { r, c ->+ val top = r == range.r1; val bottom = r == range.r2; val left = c == range.c1; val right = c == range.c2+ when (preset) {+ BorderPreset.ALL -> StylePatch(left = thin, right = thin, top = thin, bottom = thin)+ BorderPreset.NONE -> StylePatch(left = none, right = none, top = none, bottom = none)+ BorderPreset.OUTER -> StylePatch(left = if (left) thin else null, right = if (right) thin else null, top = if (top) thin else null, bottom = if (bottom) thin else null)+ BorderPreset.THICK_OUTER -> StylePatch(left = if (left) thick else null, right = if (right) thick else null, top = if (top) thick else null, bottom = if (bottom) thick else null)+ BorderPreset.INNER -> StylePatch(left = if (!left) thin else null, right = if (!right) thin else null, top = if (!top) thin else null, bottom = if (!bottom) thin else null)+ BorderPreset.TOP -> if (top) StylePatch(top = thin) else null+ BorderPreset.BOTTOM -> if (bottom) StylePatch(bottom = thin) else null+ BorderPreset.LEFT -> if (left) StylePatch(left = thin) else null+ BorderPreset.RIGHT -> if (right) StylePatch(right = thin) else null+ }+ }+ }++ private fun applyStylePer(sheet: Int, range: CellRange, patchFor: (Int, Int) -> StylePatch?) {+ val wb = _state.value.workbook ?: return+ val s = wb.sheets.getOrNull(sheet) ?: return+ val changes = ArrayList<CellChange>()+ for ((r, c) in cellsIn(s, range, existingOnly = false)) {+ val p = patchFor(r, c) ?: continue+ val before = s.cell(r, c)+ val base = before?.style ?: 0+ val style = wb.styles.derive(base, p)+ val after = (before ?: CellData("", "", 0)).copy(style = style)+ if (after != before) changes.add(CellChange(r, c, before, after))+ }+ if (changes.isNotEmpty()) push(EditOp.SetCells(sheet, changes))+ }++ /** Cells of [range], capped so a whole-column selection doesn't create a million cells. */+ private fun cellsIn(s: XlsxSheet, range: CellRange, existingOnly: Boolean): List<Pair<Int, Int>> {+ val out = ArrayList<Pair<Int, Int>>()+ val rMax = minOf(range.r2, if (existingOnly || range.r2 - range.r1 > 2000) maxOf(s.maxRow, range.r1) else range.r2)+ val cMax = minOf(range.c2, if (existingOnly || range.c2 - range.c1 > 200) maxOf(s.maxCol, range.c1) else range.c2)+ for (r in range.r1..rMax) {+ if (existingOnly) {+ val row = s.rows[r] ?: continue+ for (c in row.cells.subMap(range.c1, true, cMax, true).keys) out.add(r to c)+ } else for (c in range.c1..cMax) out.add(r to c)+ if (out.size > 50_000) break+ }+ return out+ }++ fun insertLines(sheet: Int, axis: Axis, at: Int, count: Int) {+ if (count > 0) push(EditOp.Lines(sheet, axis, at, count))+ }++ fun deleteLines(sheet: Int, axis: Axis, at: Int, count: Int) {+ if (count > 0) push(EditOp.Lines(sheet, axis, at, -count))+ }++ fun setColWidth(sheet: Int, col: Int, widthChars: Float) {+ val s = _state.value.workbook?.sheets?.getOrNull(sheet) ?: return+ push(EditOp.ColWidth(sheet, col, s.cols[col]?.widthChars, widthChars))+ }++ // ── saving ─────────────────────────────────────────────────────────────────++ /** Writes the edited package to a cache file; null on failure. */+ private fun buildPatched(context: Context): File? {+ val st = _state.value+ val wb = st.workbook ?: return null+ val src = st.fileUri?.takeIf { it.scheme == "file" }?.path?.let(::File) ?: return null+ val dir = File(context.cacheDir, "sheets").apply { mkdirs() }+ val safe = st.fileName.replace(Regex("[^A-Za-z0-9._-]"), "_").ifBlank { "sheet.xlsx" }+ val out = File(dir, "edited_${System.currentTimeMillis()}_$safe")+ return runCatching { XlsxWriter.patch(src, out, wb, applied.toList()); out }.getOrElse { out.delete(); null }+ }++ sealed class SaveResult {+ data object Saved : SaveResult()+ data object NeedsSaveAs : SaveResult()+ data class Failed(val message: String) : SaveResult()+ }++ /** Save over the opened document ([target] null) or into a new one from Save As. */+ fun save(context: Context, target: Uri?, onDone: (SaveResult) -> Unit) {+ val st = _state.value+ if (st.saving || !st.editable) return+ val dest = target ?: st.sourceUri ?: return onDone(SaveResult.NeedsSaveAs)+ _state.value = st.copy(saving = true)+ viewModelScope.launch {+ val result = withContext(Dispatchers.IO) {+ val patched = buildPatched(context) ?: return@withContext SaveResult.Failed("Couldn't write the spreadsheet.")+ try {+ if (writeWithBackup(context, dest, patched)) SaveResult.Saved+ else if (target == null) SaveResult.NeedsSaveAs else SaveResult.Failed("Couldn't save to that location.")+ } finally {+ patched.delete()+ }+ }+ _state.value = _state.value.copy(saving = false)+ if (result is SaveResult.Saved) {+ savedAt = applied.size+ publish()+ }+ onDone(result)+ }+ }+/**- * Overwrite one cell. The edit lives in memory for this viewing session — the source .xlsx is- * not rewritten, because the only POI artifact on the classpath is `poi` 3.17 (HSSF/.xls), with- * no OOXML writer, so persisting would mean regenerating the workbook from scratch and dropping- * every formula, style and merge the original carries.- *- * Rows are padded out to [col] so a cell past the parsed width of its row can still be filled.+ * Copy [file] over [uri], keeping a backup of what was there until the new content has landed+ * whole, and putting it back if the write fails midway (same approach as OpenDocument.droid).*/- fun updateCell(sheetIndex: Int, row: Int, col: Int, value: String) {- val sheets = _state.value.sheets- val sheet = sheets.getOrNull(sheetIndex) ?: return- if (row !in sheet.rows.indices) return-- val newRows = sheet.rows.toMutableList()- val cells = newRows[row].toMutableList()- while (cells.size <= col) cells.add("")- cells[col] = value- newRows[row] = cells+ private fun writeWithBackup(context: Context, uri: Uri, file: File): Boolean {+ val cr = context.contentResolver+ val backup = File(context.cacheDir, "sheets/backup_${System.currentTimeMillis()}")+ val hadBackup = runCatching { cr.openInputStream(uri)?.use { i -> backup.outputStream().use { i.copyTo(it) } } != null }.getOrDefault(false)+ return try {+ val out = runCatching { cr.openOutputStream(uri, "wt") }.getOrNull()+ ?: runCatching { cr.openOutputStream(uri, "w") }.getOrNull()+ ?: return false+ out.use { o -> file.inputStream().use { it.copyTo(o) } }+ backup.delete()+ true+ } catch (e: Throwable) {+ if (hadBackup) runCatching { cr.openOutputStream(uri, "wt")?.use { o -> backup.inputStream().use { it.copyTo(o) } } }+ .onSuccess { backup.delete() }+ // A failed restore leaves the backup in cache on purpose: it may be the last copy.+ false+ }+ }- val newSheets = sheets.toMutableList()- newSheets[sheetIndex] = sheet.copy(rows = newRows)- _state.value = _state.value.copy(sheets = newSheets, isEdited = true)+ fun suggestedSaveAsName(): String {+ val n = _state.value.fileName.ifBlank { "Spreadsheet.xlsx" }+ val base = n.substringBeforeLast('.')+ return "$base (edited).xlsx"}- /** Convert the spreadsheet to a PDF (reuses the doc converter) and hand back its URI. */+ /** Convert the (edited) spreadsheet to a PDF and hand back its URI. */fun exportToPdf(context: Context, onDone: (Uri?) -> Unit) {val uri = _state.value.fileUri ?: return onDone(null)viewModelScope.launch {val out = withContext(Dispatchers.IO) {- runCatching { com.chethan616.clearpdf.utils.UniversalDocumentConverter.convertToPdf(context, uri) }.getOrNull()+ runCatching {+ val source = if (applied.isNotEmpty()) buildPatched(context)?.let { Uri.fromFile(it) } ?: uri else uri+ com.chethan616.clearpdf.utils.UniversalDocumentConverter.convertToPdf(context, source)+ }.getOrNull()}onDone(out)}}+ /** The file to share: the edited copy when there are edits, otherwise the mirror. */+ fun shareableUri(context: Context, onDone: (Uri?) -> Unit) {+ val uri = _state.value.fileUri ?: return onDone(null)+ if (applied.isEmpty()) return onDone(uri)+ viewModelScope.launch {+ val out = withContext(Dispatchers.IO) { buildPatched(context)?.let { Uri.fromFile(it) } }+ onDone(out ?: uri)+ }+ }+private fun mirrorToCache(context: Context, uri: Uri, name: String): Uri {val dir = File(context.cacheDir, "sheets").apply { mkdirs() }val safe = name.replace(Regex("[^A-Za-z0-9._-]"), "_").ifBlank { "sheet.xlsx" }diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex ef01500..7a2b565 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -523,4 +523,41 @@<!-- Spreadsheet viewer row scrubber badge (compact: "12/940", not "Row 12 / 940") --><string name="sheet_row_of">%1$d/%2$d</string>+ <!-- Spreadsheet editor -->+ <string name="sheet_edit">Edit</string>+ <string name="sheet_done">Done</string>+ <string name="sheet_save">Save</string>+ <string name="sheet_save_as">Save as</string>+ <string name="sheet_saved">Saved</string>+ <string name="sheet_save_failed">Couldn\'t save the spreadsheet</string>+ <string name="sheet_unsaved_title">Save changes?</string>+ <string name="sheet_unsaved_body">Your edits to this spreadsheet haven\'t been saved.</string>+ <string name="sheet_discard">Discard</string>+ <string name="sheet_undo">Undo</string>+ <string name="sheet_redo">Redo</string>+ <string name="sheet_bold">Bold</string>+ <string name="sheet_italic">Italic</string>+ <string name="sheet_underline">Underline</string>+ <string name="sheet_strike">Strike</string>+ <string name="sheet_text_color">Text</string>+ <string name="sheet_fill_color">Fill</string>+ <string name="sheet_align">Align</string>+ <string name="sheet_borders">Borders</string>+ <string name="sheet_number_format">Format</string>+ <string name="sheet_rows_cols">Rows</string>+ <string name="sheet_clear">Clear</string>+ <string name="sheet_wrap">Wrap text</string>+ <string name="sheet_horizontal">Horizontal</string>+ <string name="sheet_vertical">Vertical</string>+ <string name="sheet_automatic">Automatic</string>+ <string name="sheet_no_fill">No fill</string>+ <string name="sheet_insert_row_above">Insert row above</string>+ <string name="sheet_insert_row_below">Insert row below</string>+ <string name="sheet_delete_rows">Delete rows</string>+ <string name="sheet_insert_col_left">Insert column left</string>+ <string name="sheet_insert_col_right">Insert column right</string>+ <string name="sheet_delete_cols">Delete columns</string>+ <string name="sheet_formula_hint">Enter a value or =formula</string>+ <string name="sheet_read_only">This file can be viewed but not edited</string>+ <string name="sheet_invalid_value">That value isn\'t in this cell\'s list</string></resources>