Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Open Excel workbooks: gridcraft's engine and a glass grid viewer

chethan6162fc3c67cfe83
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index ba434b6..fa56d78 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -58,6 +58,12 @@
<data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.slideshow" />
<data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.template" />
<data android:mimeType="application/vnd.ms-powerpoint.presentation.macroEnabled.12" />
+ <data android:mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
+ <data android:mimeType="application/vnd.ms-excel.sheet.macroEnabled.12" />
+ <data android:mimeType="application/vnd.ms-excel.sheet.binary.macroEnabled.12" />
+ <data android:mimeType="application/vnd.oasis.opendocument.spreadsheet" />
+ <data android:mimeType="text/csv" />
+ <data android:mimeType="text/comma-separated-values" />
</intent-filter>
</activity>
@@ -97,6 +103,12 @@
<data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.slideshow" />
<data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.template" />
<data android:mimeType="application/vnd.ms-powerpoint.presentation.macroEnabled.12" />
+ <data android:mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
+ <data android:mimeType="application/vnd.ms-excel.sheet.macroEnabled.12" />
+ <data android:mimeType="application/vnd.ms-excel.sheet.binary.macroEnabled.12" />
+ <data android:mimeType="application/vnd.oasis.opendocument.spreadsheet" />
+ <data android:mimeType="text/csv" />
+ <data android:mimeType="text/comma-separated-values" />
</intent-filter>
</activity>
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt
index b204cac..97fe1f1 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt
@@ -2,7 +2,8 @@ package com.chethan616.clearpdf.engine
/**
* The kinds of file Artefact opens: PDFs, word-processor documents read by the Word engine
- * (.docx, .doc, .odt, .rtf) and presentations read by the slides engine (.pptx). The engine tells them apart by their bytes; these lists are for the
+ * (.docx, .doc, .odt, .rtf), presentations read by the slides engine (.pptx) and workbooks read
+ * by the sheets engine (.xlsx, .xlsb, .ods, .csv). The engine tells them apart by their bytes; these lists are for the
* system's pickers, file lists and names, which go by type and extension.
*/
object DocumentTypes {
@@ -27,22 +28,35 @@ object DocumentTypes {
"application/vnd.ms-powerpoint.presentation.macroEnabled.12",
)
+ /** Workbooks and tables. */
+ val SHEETS = arrayOf(
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
+ "application/vnd.ms-excel.sheet.macroEnabled.12",
+ "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
+ "application/vnd.oasis.opendocument.spreadsheet",
+ "text/csv",
+ "text/comma-separated-values",
+ "text/tab-separated-values",
+ )
+
/** Everything the viewer opens. */
- val OPENABLE = arrayOf(PDF) + WORD + SLIDES
+ val OPENABLE = arrayOf(PDF) + WORD + SLIDES + SHEETS
private val WORD_EXTENSIONS = setOf("docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf")
private val SLIDE_EXTENSIONS = setOf("pptx", "pptm", "ppsx", "ppsm", "potx", "potm")
+ private val SHEET_EXTENSIONS = setOf("xlsx", "xlsm", "xltx", "xltm", "xlsb", "ods", "csv", "tsv")
private fun extension(name: String) = name.substringAfterLast('.', "").lowercase()
fun isWordName(name: String) = extension(name) in WORD_EXTENSIONS
- /** An office document's name (Word or slides): it keeps its own extension. */
- fun isOfficeName(name: String) = extension(name) in WORD_EXTENSIONS || extension(name) in SLIDE_EXTENSIONS
+ /** An office document's name (Word, slides or a workbook): it keeps its own extension. */
+ fun isOfficeName(name: String) = extension(name).let { it in WORD_EXTENSIONS || it in SLIDE_EXTENSIONS || it in SHEET_EXTENSIONS }
/** Whether a file of type [mime] named [name] is one the viewer opens. */
fun isOpenable(mime: String?, name: String) =
- mime == PDF || mime in WORD || mime in SLIDES || extension(name) == "pdf" || isOfficeName(name)
+ mime == PDF || mime in WORD || mime in SLIDES || mime in SHEETS || extension(name) == "pdf" || isOfficeName(name)
/** A file name without its extension, as documents are titled (`Report.docx` → `Report`). */
fun title(name: String): String =
@@ -59,6 +73,12 @@ object DocumentTypes {
"pptx", "pptm" -> SLIDES[0]
"ppsx", "ppsm" -> SLIDES[1]
"potx", "potm" -> SLIDES[2]
+ "xlsx", "xltx" -> SHEETS[0]
+ "xlsm", "xltm" -> SHEETS[2]
+ "xlsb" -> SHEETS[3]
+ "ods" -> SHEETS[4]
+ "csv" -> "text/csv"
+ "tsv" -> "text/tab-separated-values"
else -> PDF
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt
index a638e2d..d1f2c92 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/ClearApp.kt
@@ -261,7 +261,12 @@ private fun Viewer(vm: AppViewModel, doc: OpenDocument) {
Modifier.fillMaxSize().windowInsetsPadding(
if (fullWidth) WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal) else WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal),
).then(if (fullWidth) Modifier else Modifier.background(pdfColors.surface)),
- ) { com.chethan616.clearpdf.ui.glass.ProvideScreenInk { ViewerScreen(vm, doc) } }
+ ) {
+ com.chethan616.clearpdf.ui.glass.ProvideScreenInk {
+ // a workbook is a grid of its own, not pages
+ if (doc.isSheets) com.chethan616.clearpdf.ui.sheets.SheetViewer(vm, doc) else ViewerScreen(vm, doc)
+ }
+ }
}
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt
index f3c8430..37433bc 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt
@@ -83,6 +83,9 @@ class OpenDocument(
/** A presentation: each page is a slide. */
val isSlides: Boolean get() = info.kind == DocumentKind.SLIDES
+ /** A workbook: drawn as a grid, not pages. */
+ val isSheets: Boolean get() = info.kind == DocumentKind.SHEETS
+
/** The file name without its extension, as the reference titles documents. */
val title: String get() = com.chethan616.clearpdf.engine.DocumentTypes.title(info.name)
val name: String get() = info.name
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
new file mode 100644
index 0000000..c6b68ff
--- /dev/null
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/sheets/SheetViewer.kt
@@ -0,0 +1,388 @@
+package com.chethan616.clearpdf.ui.sheets
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.gestures.detectTransformGestures
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBars
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.windowInsetsBottomHeight
+import androidx.compose.foundation.layout.windowInsetsTopHeight
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateMapOf
+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.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.clipRect
+import androidx.compose.ui.graphics.drawscope.translate
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.TextMeasurer
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.drawText
+import androidx.compose.ui.text.font.FontStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.rememberTextMeasurer
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Constraints
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.core.CellSpan
+import com.chethan616.clearpdf.core.CellView
+import com.chethan616.clearpdf.core.SheetInfo
+import com.chethan616.clearpdf.ui.AppViewModel
+import com.chethan616.clearpdf.ui.LucideIcons
+import com.chethan616.clearpdf.ui.OpenDocument
+import com.chethan616.clearpdf.ui.glass.GlassChip
+import com.chethan616.clearpdf.ui.glass.GlassCircle
+import com.chethan616.clearpdf.ui.glass.GlassIcon
+import com.chethan616.clearpdf.ui.glass.GlassLoader
+import com.chethan616.clearpdf.ui.glass.LocalBackdrop
+import com.chethan616.clearpdf.ui.glass.glassBar
+import com.chethan616.clearpdf.ui.theme.ClearType
+import com.chethan616.clearpdf.ui.theme.clear
+import com.kyant.backdrop.backdrops.layerBackdrop
+import com.kyant.backdrop.backdrops.rememberLayerBackdrop
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlin.math.max
+import kotlin.math.min
+
+/** Rows and columns fetched together from the engine. */
+private const val BLOCK_ROWS = 50
+private const val BLOCK_COLS = 20
+
+/** How many rows and columns past the used area the grid still shows (room to look around). */
+private const val SPARE_ROWS = 40
+private const val SPARE_COLS = 8
+
+/** The heading strips: column letters on top, row numbers at the left (points). */
+private const val HEAD_H = 20f
+private const val HEAD_W = 36f
+
+/** One sheet's layout: where every row and column starts (points from A1), its merges and freeze. */
+private class SheetLayout(val info: SheetInfo, val colX: FloatArray, val rowY: FloatArray, val merges: List<CellSpan>) {
+ val cols get() = colX.size - 1
+ val rows get() = rowY.size - 1
+
+ /** The first index whose start is past [v] in [edges], less one: the line [v] falls in. */
+ fun indexAt(edges: FloatArray, v: Float): Int {
+ var lo = 0
+ var hi = edges.size - 1
+ while (lo < hi) {
+ val mid = (lo + hi + 1) / 2
+ if (edges[mid] <= v) lo = mid else hi = mid - 1
+ }
+ return lo.coerceAtMost(edges.size - 2).coerceAtLeast(0)
+ }
+}
+
+/** "A", "B", …, "Z", "AA", … */
+private fun columnName(c: Int): String {
+ var n = c + 1
+ val sb = StringBuilder()
+ while (n > 0) {
+ val r = (n - 1) % 26
+ sb.insert(0, 'A' + r)
+ n = (n - 1) / 26
+ }
+ return sb.toString()
+}
+
+private fun rgb(c: UInt): Color = Color(0xFF000000.toInt() or c.toInt())
+
+/**
+ * A workbook: its sheets as a grid that pans and zooms under glass bars, the heading strips and
+ * the frozen panes held in place, a sheet chosen from the tabs at the bottom.
+ */
+@Composable
+fun SheetViewer(vm: AppViewModel, doc: OpenDocument) {
+ val eng = vm.engine ?: return
+ val c = clear
+ var sheets by remember { mutableStateOf<List<SheetInfo>>(emptyList()) }
+ var current by remember { mutableIntStateOf(0) }
+ var layout by remember { mutableStateOf<SheetLayout?>(null) }
+ // blocks of cells by (sheet, block row, block column), filled in as they come into view
+ val blocks = remember { mutableStateMapOf<Triple<Int, Int, Int>, List<CellView>>() }
+ var scale by remember { mutableStateOf(1f) }
+ var pan by remember { mutableStateOf(Offset.Zero) }
+ val density = LocalDensity.current
+ // the grid starts under the top row of glass (it runs on beneath it, for the glass to refract)
+ val topPx = with(density) { WindowInsets.statusBars.getTop(this) + 64.dp.toPx() }
+
+ LaunchedEffect(doc.id) {
+ sheets = runCatching { eng.command { sheets(doc.id) } }.getOrDefault(emptyList())
+ current = sheets.indexOfFirst { !it.hidden }.coerceAtLeast(0)
+ }
+ LaunchedEffect(sheets, current) {
+ val info = sheets.getOrNull(current) ?: return@LaunchedEffect
+ layout = null
+ pan = Offset.Zero
+ val rows = min(info.rows.toInt() + SPARE_ROWS, 20_000)
+ val cols = min(info.cols.toInt() + SPARE_COLS, 2_000)
+ val l = runCatching {
+ eng.command {
+ val axes = sheetAxes(doc.id, current.toUInt(), 0u, rows.toUInt(), 0u, cols.toUInt())
+ val colX = FloatArray(cols + 1).also { a -> axes.colWidths.forEachIndexed { i, w -> a[i + 1] = a[i] + w } }
+ val rowY = FloatArray(rows + 1).also { a -> axes.rowHeights.forEachIndexed { i, h -> a[i + 1] = a[i] + h } }
+ SheetLayout(info, colX, rowY, sheetMerges(doc.id, current.toUInt()))
+ }
+ }.getOrNull()
+ layout = l
+ }
+
+ val backdrop = rememberLayerBackdrop()
+ val measurer = rememberTextMeasurer(cacheSize = 256)
+ val sheetIndex = current
+ Box(Modifier.fillMaxSize()) {
+ // the grid, recorded as the bars' backdrop: their glass refracts the cells
+ Box(Modifier.fillMaxSize().layerBackdrop(backdrop)) {
+ val l = layout
+ if (l == null) {
+ Box(Modifier.fillMaxSize().padding(top = 120.dp), contentAlignment = Alignment.TopCenter) { GlassLoader(size = 64.dp) }
+ } else {
+ val px = density.density
+ // the blocks in view, asked for as the grid moves
+ LaunchedEffect(l) {
+ snapshotFlow { Triple(pan, scale, l) }
+ .distinctUntilChanged()
+ .collect { (p, s, lay) ->
+ val k = px * s
+ val x0 = (-p.x / k).coerceAtLeast(0f)
+ val y0 = (-p.y / k).coerceAtLeast(0f)
+ val c0 = lay.indexAt(lay.colX, x0) / BLOCK_COLS
+ val r0 = lay.indexAt(lay.rowY, y0) / BLOCK_ROWS
+ for (br in r0..r0 + 1) for (bc in c0..c0 + 1) {
+ val key = Triple(sheetIndex, br, bc)
+ if (key in blocks || br * BLOCK_ROWS >= lay.rows || bc * BLOCK_COLS >= lay.cols) continue
+ blocks[key] = emptyList()
+ blocks[key] = runCatching {
+ eng.command { sheetCells(doc.id, sheetIndex.toUInt(), (br * BLOCK_ROWS).toUInt(), BLOCK_ROWS.toUInt(), (bc * BLOCK_COLS).toUInt(), BLOCK_COLS.toUInt()) }
+ }.getOrDefault(emptyList())
+ }
+ }
+ }
+ Canvas(
+ Modifier
+ .fillMaxSize()
+ .pointerInput(l) {
+ detectTransformGestures { centroid, move, zoom, _ ->
+ val s = (scale * zoom).coerceIn(0.4f, 4f)
+ val f = s / scale
+ val k = px * s
+ val maxX = (l.colX.last() * k - size.width / 2f).coerceAtLeast(0f)
+ val maxY = (l.rowY.last() * k - size.height / 2f).coerceAtLeast(0f)
+ // zoom about the fingers, then follow them
+ val p = (pan - centroid) * f + centroid + move
+ pan = Offset(p.x.coerceIn(-maxX, 0f), p.y.coerceIn(-maxY, 0f))
+ scale = s
+ }
+ }
+ .pointerInput(Unit) { detectTapGestures(onDoubleTap = { scale = if (scale > 1.2f) 1f else 2f; pan = Offset.Zero }) },
+ ) {
+ drawRect(Color.White)
+ translate(top = topPx) { drawSheet(l, blocks, sheetIndex, px * scale, pan, measurer, c.ink) }
+ }
+ }
+ }
+ CompositionLocalProvider(LocalBackdrop provides backdrop) {
+ // the top row: back, the workbook's title and the sheet shown, share
+ Column(Modifier.fillMaxWidth().align(Alignment.TopCenter)) {
+ Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
+ Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) {
+ GlassCircle(onClick = { vm.closeDocument() }, label = stringResource(R.string.common_back)) { GlassIcon(LucideIcons.ChevronLeft, null, Modifier.size(22.dp)) }
+ Spacer(Modifier.size(10.dp))
+ Column(Modifier.weight(1f).glassBar().padding(horizontal = 16.dp, vertical = 6.dp)) {
+ Text(doc.title, style = ClearType.BodyStrong, color = c.ink, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ sheets.getOrNull(current)?.let { Text(it.name, style = ClearType.Caption, color = c.inkSoft, maxLines = 1) }
+ }
+ Spacer(Modifier.size(10.dp))
+ GlassCircle(onClick = { vm.share(doc) }, label = stringResource(R.string.common_share)) { GlassIcon(LucideIcons.Share2, null, Modifier.size(20.dp)) }
+ }
+ }
+ // the sheet tabs
+ val visible = sheets.withIndex().filter { !it.value.hidden }
+ if (visible.size > 1) Column(Modifier.fillMaxWidth().align(Alignment.BottomCenter)) {
+ Row(
+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp, vertical = 8.dp),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ ) {
+ for ((i, s) in visible) {
+ val chosen = i == current
+ GlassChip(
+ onClick = { current = i },
+ fill = if (chosen) ({ com.chethan616.clearpdf.ui.theme.Candy.Lemon }) else s.tabColor?.let { t -> { rgb(t).copy(alpha = 0.35f) } },
+ ink = if (chosen) Color(0xFF172033) else c.ink,
+ ) { Text(s.name, style = ClearType.Body.copy(fontSize = 14.sp), maxLines = 1) }
+ }
+ }
+ Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars))
+ }
+ }
+ }
+}
+
+/**
+ * The sheet at [k] pixels per point, moved by [pan]: the body, then the frozen rows and columns
+ * held still on their axis, then the heading strips, each clipped to its own region.
+ */
+private fun DrawScope.drawSheet(
+ l: SheetLayout,
+ blocks: Map<Triple<Int, Int, Int>, List<CellView>>,
+ sheet: Int,
+ k: Float,
+ pan: Offset,
+ measurer: TextMeasurer,
+ ink: Color,
+) {
+ val head = Offset(HEAD_W * k.coerceAtMost(density * 1.5f), HEAD_H * k.coerceAtMost(density * 1.5f))
+ val fr = min(l.info.frozenRows.toInt(), l.rows)
+ val fc = min(l.info.frozenCols.toInt(), l.cols)
+ val frozenW = l.colX[fc] * k
+ val frozenH = l.rowY[fr] * k
+ val body = Rect(head.x + frozenW, head.y + frozenH, size.width, size.height)
+ // a region of the sheet: rows/columns from the given starts, drawn from [origin]
+ fun region(clip: Rect, origin: Offset, rowsFrom: Int, rowsTo: Int, colsFrom: Int, colsTo: Int, scrollX: Boolean, scrollY: Boolean) {
+ if (clip.width <= 0f || clip.height <= 0f) return
+ val ox = origin.x + (if (scrollX) pan.x else 0f)
+ val oy = origin.y + (if (scrollY) pan.y else 0f)
+ // the lines in view
+ val c0 = max(colsFrom, l.indexAt(l.colX, (clip.left - ox) / k))
+ val c1 = min(colsTo, l.indexAt(l.colX, (clip.right - ox) / k) + 1)
+ val r0 = max(rowsFrom, l.indexAt(l.rowY, (clip.top - oy) / k))
+ val r1 = min(rowsTo, l.indexAt(l.rowY, (clip.bottom - oy) / k) + 1)
+ if (c0 >= c1 || r0 >= r1) return
+ clipRect(clip.left, clip.top, clip.right, clip.bottom) {
+ val cell = { r: Int, c: Int -> Rect(ox + l.colX[c] * k, oy + l.rowY[r] * k, ox + l.colX[c + 1] * k, oy + l.rowY[r + 1] * k) }
+ // grid lines
+ if (l.info.gridlines) {
+ val line = Color(0xFFE1E4EA)
+ for (c in c0..c1) drawLine(line, Offset(ox + l.colX[c] * k, clip.top), Offset(ox + l.colX[c] * k, clip.bottom), 1f)
+ for (r in r0..r1) drawLine(line, Offset(clip.left, oy + l.rowY[r] * k), Offset(clip.right, oy + l.rowY[r] * k), 1f)
+ }
+ // the cells of the blocks in view: fills, then borders, then text
+ val shown = ArrayList<CellView>()
+ for (br in r0 / BLOCK_ROWS..(r1 - 1) / BLOCK_ROWS) for (bc in c0 / BLOCK_COLS..(c1 - 1) / BLOCK_COLS) {
+ blocks[Triple(sheet, br, bc)]?.forEach { v -> if (v.row.toInt() in r0 until r1 && v.col.toInt() in c0 until c1) shown += v }
+ }
+ fun spanOf(v: CellView): Rect {
+ val m = l.merges.firstOrNull { it.row0 == v.row && it.col0 == v.col }
+ return if (m == null) cell(v.row.toInt(), v.col.toInt())
+ else cell(m.row0.toInt(), m.col0.toInt()).let { a ->
+ val b = cell(min(m.row1.toInt(), l.rows - 1), min(m.col1.toInt(), l.cols - 1))
+ Rect(a.left, a.top, b.right, b.bottom)
+ }
+ }
+ for (v in shown) v.fill?.let { drawRect(rgb(it), spanOf(v).topLeft, spanOf(v).size) }
+ for (v in shown) {
+ val r = spanOf(v)
+ fun edge(e: com.chethan616.clearpdf.core.CellEdge, a: Offset, b: Offset) {
+ if (e.weight > 0u) drawLine(rgb(e.color), a, b, e.weight.toFloat() * density * 0.6f)
+ }
+ edge(v.left, r.topLeft, r.bottomLeft)
+ edge(v.top, r.topLeft, r.topRight)
+ edge(v.right, r.topRight, r.bottomRight)
+ edge(v.bottom, r.bottomLeft, r.bottomRight)
+ }
+ for (v in shown) {
+ if (v.text.isEmpty()) continue
+ val r = spanOf(v)
+ val pad = 2f * k
+ val maxW = (r.width - 2 * pad).toInt()
+ if (maxW <= 0) continue
+ val style = TextStyle(
+ color = rgb(v.ink),
+ fontSize = (v.size * k / density / fontScale).sp,
+ fontWeight = if (v.bold) FontWeight.Bold else FontWeight.Normal,
+ fontStyle = if (v.italic) FontStyle.Italic else FontStyle.Normal,
+ textDecoration = when {
+ v.underline && v.strike -> TextDecoration.combine(listOf(TextDecoration.Underline, TextDecoration.LineThrough))
+ v.underline -> TextDecoration.Underline
+ v.strike -> TextDecoration.LineThrough
+ else -> null
+ },
+ )
+ val t = measurer.measure(
+ v.text, style,
+ overflow = TextOverflow.Clip,
+ softWrap = v.wrap, maxLines = if (v.wrap) Int.MAX_VALUE else 1,
+ constraints = Constraints(maxWidth = if (v.wrap) maxW else Constraints.Infinity, maxHeight = max(1, r.height.toInt())),
+ )
+ val w = t.size.width.toFloat()
+ val x = when (v.align) {
+ "c" -> r.left + (r.width - w) / 2f
+ "r" -> r.right - pad - w
+ else -> r.left + pad
+ }
+ val y = when (v.valign) {
+ "t" -> r.top + pad / 2
+ "c" -> r.top + (r.height - t.size.height) / 2f
+ else -> r.bottom - pad / 2 - t.size.height
+ }
+ // text stays within its cell (a neighbour's text would overlap it otherwise)
+ clipRect(r.left, r.top, r.right, r.bottom) { drawText(t, topLeft = Offset(x, y)) }
+ }
+ }
+ }
+ // body, then the frozen strips, then the corner where both are frozen
+ region(body, head, fr, l.rows, fc, l.cols, scrollX = true, scrollY = true)
+ region(Rect(head.x + frozenW, head.y, size.width, head.y + frozenH), head, 0, fr, fc, l.cols, scrollX = true, scrollY = false)
+ region(Rect(head.x, head.y + frozenH, head.x + frozenW, size.height), head, fr, l.rows, 0, fc, scrollX = false, scrollY = true)
+ region(Rect(head.x, head.y, head.x + frozenW, head.y + frozenH), head, 0, fr, 0, fc, scrollX = false, scrollY = false)
+ if (fr > 0) drawLine(Color(0xFF9AA3B2), Offset(head.x, head.y + frozenH), Offset(size.width, head.y + frozenH), density)
+ if (fc > 0) drawLine(Color(0xFF9AA3B2), Offset(head.x + frozenW, head.y), Offset(head.x + frozenW, size.height), density)
+ // the heading strips
+ val strip = Color(0xFFF2F4F8)
+ val label = TextStyle(color = ink.copy(alpha = 0.6f), fontSize = (11 * min(k / density, 1.5f) / fontScale).sp)
+ drawRect(strip, Offset(0f, 0f), Size(size.width, head.y))
+ drawRect(strip, Offset(0f, 0f), Size(head.x, size.height))
+ val lineC = Color(0xFFD5D9E0)
+ clipRect(head.x, 0f, size.width, head.y) {
+ for (c in 0 until l.cols) {
+ val x0 = head.x + l.colX[c] * k + (if (c >= fc) pan.x else 0f)
+ val x1 = head.x + l.colX[c + 1] * k + (if (c >= fc) pan.x else 0f)
+ if (x1 < head.x + (if (c >= fc) frozenW else 0f) || x0 > size.width || x1 - x0 < 1f) continue
+ drawLine(lineC, Offset(x1, 0f), Offset(x1, head.y), 1f)
+ val t = measurer.measure(columnName(c), label)
+ if (t.size.width < x1 - x0) drawText(t, topLeft = Offset((x0 + x1 - t.size.width) / 2f, (head.y - t.size.height) / 2f))
+ }
+ }
+ clipRect(0f, head.y, head.x, size.height) {
+ for (r in 0 until l.rows) {
+ val y0 = head.y + l.rowY[r] * k + (if (r >= fr) pan.y else 0f)
+ val y1 = head.y + l.rowY[r + 1] * k + (if (r >= fr) pan.y else 0f)
+ if (y1 < head.y + (if (r >= fr) frozenH else 0f) || y0 > size.height || y1 - y0 < 1f) continue
+ drawLine(lineC, Offset(0f, y1), Offset(head.x, y1), 1f)
+ val t = measurer.measure((r + 1).toString(), label)
+ if (t.size.height < y1 - y0 + 2) drawText(t, topLeft = Offset((head.x - t.size.width) / 2f, (y0 + y1 - t.size.height) / 2f))
+ }
+ }
+ drawLine(lineC, Offset(0f, head.y), Offset(size.width, head.y), 1f)
+ drawLine(lineC, Offset(head.x, 0f), Offset(head.x, size.height), 1f)
+}
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 7603674..de6e6e0 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -131,13 +131,15 @@ dependencies = [
"deckcraft-model",
"deckcraft-pptx",
"deckcraft-render",
+ "gridcraft-engine",
+ "gridcraft-xlsx",
"kurbo",
"log",
"pdfcraft-automation",
"pdfcraft-engine",
"pdfcraft-render",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
"uniffi",
"wordcraft-engine",
]
@@ -533,7 +535,7 @@ dependencies = [
"tag_ptr",
"tap",
"thin-vec",
- "thiserror",
+ "thiserror 2.0.21",
"time",
"web-time",
]
@@ -735,7 +737,7 @@ dependencies = [
"semver",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -1025,7 +1027,7 @@ version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
dependencies = [
"krilla",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -1257,7 +1259,7 @@ source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7
dependencies = [
"image",
"kurbo",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -1269,7 +1271,7 @@ dependencies = [
"deckcraft-geom",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
"unicode-segmentation",
]
@@ -1283,7 +1285,7 @@ dependencies = [
"deckcraft-model",
"log",
"quick-xml",
- "thiserror",
+ "thiserror 2.0.21",
"zip",
]
@@ -1635,6 +1637,17 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "fancy-regex"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298"
+dependencies = [
+ "bit-set",
+ "regex-automata",
+ "regex-syntax",
+]
+
[[package]]
name = "fast-float2"
version = "0.2.4"
@@ -2005,6 +2018,139 @@ dependencies = [
"scroll",
]
+[[package]]
+name = "gridcraft-calc"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-core",
+ "gridcraft-formula",
+ "gridcraft-functions",
+ "gridcraft-model",
+ "gridcraft-numfmt",
+ "log",
+]
+
+[[package]]
+name = "gridcraft-chart"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-calc",
+ "gridcraft-core",
+ "gridcraft-model",
+ "gridcraft-numfmt",
+ "serde",
+]
+
+[[package]]
+name = "gridcraft-core"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "chrono",
+ "js-sys",
+ "serde",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "gridcraft-engine"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-calc",
+ "gridcraft-chart",
+ "gridcraft-core",
+ "gridcraft-formula",
+ "gridcraft-functions",
+ "gridcraft-math",
+ "gridcraft-model",
+ "gridcraft-numfmt",
+ "gridcraft-pdf",
+ "gridcraft-xlsx",
+ "image",
+ "log",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+ "web-time",
+]
+
+[[package]]
+name = "gridcraft-formula"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-core",
+ "serde",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "gridcraft-functions"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-core",
+ "regex",
+]
+
+[[package]]
+name = "gridcraft-math"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "ratex-font",
+ "ratex-layout",
+ "ratex-parser",
+ "ratex-types",
+]
+
+[[package]]
+name = "gridcraft-model"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-core",
+ "gridcraft-formula",
+ "gridcraft-math",
+ "serde",
+ "serde_json",
+ "sha2 0.11.0",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "gridcraft-numfmt"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "gridcraft-core",
+]
+
+[[package]]
+name = "gridcraft-pdf"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+
+[[package]]
+name = "gridcraft-xlsx"
+version = "0.16.0"
+source = "git+https://github.com/storytold/gridcraft?rev=6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214#6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214"
+dependencies = [
+ "aes",
+ "gridcraft-core",
+ "gridcraft-formula",
+ "gridcraft-math",
+ "gridcraft-model",
+ "quick-xml",
+ "sha1 0.11.0",
+ "sha2 0.11.0",
+ "thiserror 2.0.21",
+ "zip",
+]
+
[[package]]
name = "group"
version = "0.14.0"
@@ -2542,7 +2688,7 @@ dependencies = [
"jni-sys",
"log",
"simd_cesu8",
- "thiserror",
+ "thiserror 2.0.21",
"walkdir",
"windows-link",
]
@@ -2711,7 +2857,7 @@ dependencies = [
"rayon",
"sha2 0.11.0",
"stringprep",
- "thiserror",
+ "thiserror 2.0.21",
"weezl 0.2.1",
]
@@ -2911,7 +3057,7 @@ dependencies = [
"rten",
"rten-imageproc",
"rten-tensor",
- "thiserror",
+ "thiserror 2.0.21",
"wasm-bindgen",
]
@@ -3049,7 +3195,7 @@ dependencies = [
"pdfcraft-filters",
"pdfcraft-fonts",
"pdfcraft-model",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3060,7 +3206,7 @@ dependencies = [
"pdfcraft-cos",
"pdfcraft-fonts",
"pdfcraft-model",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3071,7 +3217,7 @@ dependencies = [
"pdfcraft-cos",
"pdfcraft-edit",
"pdfcraft-model",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3120,7 +3266,7 @@ dependencies = [
"pdfcraft-testkit",
"proptest",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3137,7 +3283,7 @@ dependencies = [
"pdfcraft-model",
"png",
"roxmltree",
- "thiserror",
+ "thiserror 2.0.21",
"tiff",
"zune-jpeg",
]
@@ -3151,7 +3297,7 @@ dependencies = [
"proptest",
"sha2 0.11.0",
"stringprep",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3165,7 +3311,7 @@ dependencies = [
"pdfcraft-cos",
"pdfcraft-fonts",
"pdfcraft-model",
- "thiserror",
+ "thiserror 2.0.21",
"unicode-bidi",
]
@@ -3204,7 +3350,7 @@ dependencies = [
"pdfcraft-xfa",
"pdfcraft-xfdf",
"png",
- "thiserror",
+ "thiserror 2.0.21",
"tiff",
"unicode-segmentation",
"url",
@@ -3223,7 +3369,7 @@ version = "0.14.0"
dependencies = [
"flate2",
"proptest",
- "thiserror",
+ "thiserror 2.0.21",
"weezl 0.2.1",
]
@@ -3247,7 +3393,7 @@ dependencies = [
"pdfcraft-fonts",
"pdfcraft-model",
"proptest",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3272,7 +3418,7 @@ dependencies = [
"pdfcraft-model",
"pdfcraft-testkit",
"serde",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3289,7 +3435,7 @@ dependencies = [
"ocrs",
"pdfcraft-fonts",
"rten",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3303,7 +3449,7 @@ dependencies = [
"pdfcraft-filters",
"pdfcraft-model",
"pdfcraft-render",
- "thiserror",
+ "thiserror 2.0.21",
"zune-jpeg",
]
@@ -3319,7 +3465,7 @@ dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-oracle",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3352,7 +3498,7 @@ dependencies = [
"pdfcraft-cos",
"pdfcraft-model",
"pdfcraft-render",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3368,7 +3514,7 @@ dependencies = [
"pdfcraft-model",
"pdfcraft-testkit",
"pdfcraft-xfa",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3387,7 +3533,7 @@ dependencies = [
"pdfcraft-fonts",
"serde",
"skrifa 0.44.0",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3423,7 +3569,7 @@ dependencies = [
"sha1 0.11.0",
"sha2 0.11.0",
"sha3",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3441,7 +3587,7 @@ dependencies = [
"png",
"roxmltree",
"sha2 0.11.0",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3453,7 +3599,7 @@ dependencies = [
"pdfcraft-forms",
"pdfcraft-model",
"roxmltree",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -3503,6 +3649,16 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "phf"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
+dependencies = [
+ "phf_macros 0.11.3",
+ "phf_shared 0.11.3",
+]
+
[[package]]
name = "phf"
version = "0.13.1"
@@ -3523,6 +3679,16 @@ dependencies = [
"phf_shared 0.14.0",
]
+[[package]]
+name = "phf_generator"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
+dependencies = [
+ "phf_shared 0.11.3",
+ "rand 0.8.8",
+]
+
[[package]]
name = "phf_generator"
version = "0.13.1"
@@ -3543,6 +3709,19 @@ dependencies = [
"phf_shared 0.14.0",
]
+[[package]]
+name = "phf_macros"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216"
+dependencies = [
+ "phf_generator 0.11.3",
+ "phf_shared 0.11.3",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "phf_macros"
version = "0.13.1"
@@ -3569,6 +3748,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "phf_shared"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5"
+dependencies = [
+ "siphasher",
+]
+
[[package]]
name = "phf_shared"
version = "0.13.1"
@@ -3861,7 +4049,7 @@ dependencies = [
"rustc-hash",
"rustls",
"socket2",
- "thiserror",
+ "thiserror 2.0.21",
"tokio",
"tracing",
"web-time",
@@ -3884,7 +4072,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"slab",
- "thiserror",
+ "thiserror 2.0.21",
"tinyvec",
"tracing",
"web-time",
@@ -3925,6 +4113,15 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+[[package]]
+name = "rand"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
+dependencies = [
+ "rand_core 0.6.4",
+]
+
[[package]]
name = "rand"
version = "0.9.5"
@@ -4001,6 +4198,66 @@ version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
+[[package]]
+name = "ratex-font"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a7b73531dabe934a3e725ed5c90d18dacf43778b7a208381390943a9a8c24db"
+dependencies = [
+ "phf 0.11.3",
+ "ratex-types",
+]
+
+[[package]]
+name = "ratex-layout"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1792738e2e36683cd20de742296a5233759565efc8cd03831064a0ccfb1fe0f7"
+dependencies = [
+ "ratex-font",
+ "ratex-parser",
+ "ratex-types",
+ "serde_json",
+]
+
+[[package]]
+name = "ratex-lexer"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f704add86d7bf4c4ecc7767f45ab38a44f1bbfa4b49725b2ae53c32e83b8a61e"
+dependencies = [
+ "ratex-types",
+ "serde",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ratex-parser"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "079ec2e7ac6bc76137a6de093a173d1f901139a51318589ab9ce17139c21a6f0"
+dependencies = [
+ "fancy-regex",
+ "ratex-font",
+ "ratex-lexer",
+ "ratex-types",
+ "regex",
+ "regex-lite",
+ "serde",
+ "serde_json",
+ "thiserror 1.0.69",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "ratex-types"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cf0be3d050525f0f7d37af55a443d7648c222ccc617639950e3de1f8e6f9900"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "rayon"
version = "1.12.0"
@@ -4105,6 +4362,12 @@ dependencies = [
"regex-syntax",
]
+[[package]]
+name = "regex-lite"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
+
[[package]]
name = "regex-syntax"
version = "0.8.11"
@@ -4765,7 +5028,7 @@ dependencies = [
"sigstore-rekor",
"sigstore-tsa",
"sigstore-types",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -4785,7 +5048,7 @@ dependencies = [
"signature 2.2.0",
"sigstore-types",
"spki 0.7.3",
- "thiserror",
+ "thiserror 2.0.21",
"tracing",
"x509-cert",
]
@@ -4800,7 +5063,7 @@ dependencies = [
"hex",
"sigstore-crypto",
"sigstore-types",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -4817,7 +5080,7 @@ dependencies = [
"sigstore-crypto",
"sigstore-merkle",
"sigstore-types",
- "thiserror",
+ "thiserror 2.0.21",
"url",
]
@@ -4835,7 +5098,7 @@ dependencies = [
"serde_json",
"sigstore-crypto",
"sigstore-types",
- "thiserror",
+ "thiserror 2.0.21",
"x509-cert",
]
@@ -4859,7 +5122,7 @@ dependencies = [
"rustls-webpki",
"sigstore-crypto",
"sigstore-types",
- "thiserror",
+ "thiserror 2.0.21",
"tracing",
"x509-cert",
"x509-tsp",
@@ -4877,7 +5140,7 @@ dependencies = [
"pem",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -4904,7 +5167,7 @@ dependencies = [
"sigstore-trust-root",
"sigstore-tsa",
"sigstore-types",
- "thiserror",
+ "thiserror 2.0.21",
"tls_codec",
"tracing",
"x509-cert",
@@ -5233,13 +5496,33 @@ version = "0.2.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4568d7e143ec86d2021c338bae2afa88699e84b8e0af523626654fe6f03a1748"
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
- "thiserror-impl",
+ "thiserror-impl 2.0.21",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
]
[[package]]
@@ -5788,7 +6071,7 @@ dependencies = [
"peniko",
"png",
"smallvec",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -5805,7 +6088,7 @@ dependencies = [
"peniko",
"png",
"smallvec",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -5821,7 +6104,7 @@ dependencies = [
"peniko",
"png",
"smallvec",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -6242,7 +6525,7 @@ dependencies = [
"sigstore-verify",
"strum",
"tar",
- "thiserror",
+ "thiserror 2.0.21",
"windows",
"windows-core",
"windows-implement",
@@ -6282,7 +6565,7 @@ dependencies = [
"log",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
"unicode-segmentation",
"wordcraft-geom",
]
@@ -6298,7 +6581,7 @@ dependencies = [
"log",
"miniz_oxide 0.9.1",
"sha1 0.11.0",
- "thiserror",
+ "thiserror 2.0.21",
"wordcraft-doc",
"wordcraft-geom",
]
@@ -6318,7 +6601,7 @@ dependencies = [
"quick-xml",
"sha1 0.11.0",
"sha2 0.11.0",
- "thiserror",
+ "thiserror 2.0.21",
"unicode-bidi",
"wordcraft-doc",
"wordcraft-geom",
@@ -6341,7 +6624,7 @@ dependencies = [
"regex-automata",
"serde",
"serde_json",
- "thiserror",
+ "thiserror 2.0.21",
"wordcraft-doc",
"wordcraft-docbin",
"wordcraft-docx",
@@ -6431,7 +6714,7 @@ version = "0.15.1"
source = "git+https://github.com/storytold/wordcraft?rev=729cd0a5fc953bbedbfdec4f6af18ad6d1780b3b#729cd0a5fc953bbedbfdec4f6af18ad6d1780b3b"
dependencies = [
"kurbo",
- "thiserror",
+ "thiserror 2.0.21",
]
[[package]]
@@ -6445,7 +6728,7 @@ dependencies = [
"js-sys",
"kurbo",
"log",
- "thiserror",
+ "thiserror 2.0.21",
"wordcraft-doc",
"wordcraft-fonts",
"wordcraft-geom",
diff --git a/engine/Cargo.toml b/engine/Cargo.toml
index 647985d..e9bedd4 100644
--- a/engine/Cargo.toml
+++ b/engine/Cargo.toml
@@ -66,6 +66,10 @@ deckcraft-model = { git = "https://github.com/storytold/deckcraft", rev = "159ed
deckcraft-pptx = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }
deckcraft-render = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }
+# Excel (.xlsx, .xlsb, .ods, .csv): storytold/gridcraft's engine (formulas, number formats), pinned.
+gridcraft-engine = { git = "https://github.com/storytold/gridcraft", rev = "6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214", version = "0.16.0" }
+gridcraft-xlsx = { git = "https://github.com/storytold/gridcraft", rev = "6a8eb4ff42cfa88b5bdd3eec13c6db3874d95214", version = "0.16.0" }
+
# pdf
hayro = "0.7.1"
hayro-syntax = "0.7.2"
diff --git a/engine/mobile/Cargo.toml b/engine/mobile/Cargo.toml
index 58eb9b4..b1bb620 100644
--- a/engine/mobile/Cargo.toml
+++ b/engine/mobile/Cargo.toml
@@ -26,6 +26,9 @@ wordcraft-engine = { workspace = true }
deckcraft-model = { workspace = true }
deckcraft-pptx = { workspace = true }
deckcraft-render = { workspace = true }
+# Excel workbooks (src/sheets.rs): GridCraft's engine
+gridcraft-engine = { workspace = true }
+gridcraft-xlsx = { workspace = true }
kurbo = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rs
index 3012203..f8d5467 100644
--- a/engine/mobile/src/lib.rs
+++ b/engine/mobile/src/lib.rs
@@ -26,7 +26,10 @@ use serde_json::{Value, json};
uniffi::setup_scaffolding!();
mod office;
+mod sheets;
mod slides;
+
+pub use sheets::{CellEdge, CellSpan, CellView, SheetAxes, SheetInfo};
#[cfg(test)]
mod tests;
mod word;
@@ -76,6 +79,9 @@ pub enum DocumentKind {
Word,
/// A presentation (.pptx), read by DeckCraft: each slide is a page.
Slides,
+ /// A workbook (.xlsx, .xlsb, .ods, .csv), read by GridCraft: each sheet is a page, drawn by the
+ /// app as a grid of its own (see [`MobileSession::sheets`]).
+ Sheets,
}
/// An open document as the viewer's title, menus and properties show it.
@@ -499,6 +505,12 @@ impl MobileSession {
self.office.lock().unwrap_or_else(PoisonError::into_inner).get(&doc).cloned()
}
+ /// Run `f` on workbook `doc`.
+ fn with_sheets<T>(&self, doc: u64, f: impl FnOnce(&sheets::SheetBook) -> Result<T, MobileError>) -> Result<T, MobileError> {
+ let d = self.office(doc).ok_or(MobileError::NoDocument(doc))?;
+ d.as_sheets().ok_or(MobileError::NoDocument(doc)).and_then(f)
+ }
+
fn with_doc<T>(&self, doc: u64, f: impl FnOnce(&Document) -> T) -> Result<T, MobileError> {
let a = self.lock();
let d = a.session().get(DocId(doc)).ok_or(MobileError::NoDocument(doc))?;
@@ -864,6 +876,31 @@ impl MobileSession {
})
}
+ /// The sheets of workbook `doc`, in tab order.
+ pub fn sheets(&self, doc: u64) -> Result<Vec<SheetInfo>, MobileError> {
+ self.with_sheets(doc, |b| Ok(b.sheets()))
+ }
+
+ /// Column widths and row heights (points) of a window of sheet `sheet`.
+ pub fn sheet_axes(&self, doc: u64, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<SheetAxes, MobileError> {
+ self.with_sheets(doc, |b| b.axes(sheet, row0, rows, col0, cols))
+ }
+
+ /// The cells of a window of sheet `sheet` that show something, with their looks.
+ pub fn sheet_cells(&self, doc: u64, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<Vec<CellView>, MobileError> {
+ self.with_sheets(doc, |b| b.cells(sheet, row0, rows, col0, cols))
+ }
+
+ /// The merged areas of sheet `sheet`.
+ pub fn sheet_merges(&self, doc: u64, sheet: u32) -> Result<Vec<CellSpan>, MobileError> {
+ self.with_sheets(doc, |b| b.merges(sheet))
+ }
+
+ /// The cells of sheet `sheet` showing `query`, at most `limit`, in reading order.
+ pub fn sheet_find(&self, doc: u64, sheet: u32, query: String, case_sensitive: bool, limit: u32) -> Result<Vec<CellSpan>, MobileError> {
+ self.with_sheets(doc, |b| b.find(sheet, &query, case_sensitive, limit))
+ }
+
/// Drop the idle renderers and text layers (the system is short of memory); the next render
/// or text call makes new ones.
pub fn release_memory(&self) {
diff --git a/engine/mobile/src/office.rs b/engine/mobile/src/office.rs
index aaac883..feee168 100644
--- a/engine/mobile/src/office.rs
+++ b/engine/mobile/src/office.rs
@@ -34,6 +34,11 @@ pub(crate) trait OfficeDoc: Send + Sync {
/// Drop what can be built again (the system is short of memory).
fn release_memory(&self);
+ /// A workbook, whose sheets the app draws as a grid of its own.
+ fn as_sheets(&self) -> Option<&crate::sheets::SheetBook> {
+ None
+ }
+
/// Page 1 drawn to fit `max_side` pixels, for file lists.
fn thumbnail(&self, max_side: u32) -> Result<RenderedImage, MobileError> {
let page = self.info(0).pages.into_iter().next().ok_or_else(|| MobileError::Open("the document has no pages".into()))?;
@@ -47,10 +52,12 @@ pub(crate) trait OfficeDoc: Send + Sync {
pub(crate) enum OfficeFile {
Word(&'static str),
Slides,
+ Sheets(&'static str),
}
const WORD_EXTENSIONS: &[&str] = &["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf"];
const SLIDE_EXTENSIONS: &[&str] = &["pptx", "pptm", "ppsx", "ppsm", "potx", "potm"];
+const SHEET_EXTENSIONS: &[&str] = &["xlsx", "xlsm", "xltx", "xltm", "xlsb", "ods", "csv", "tsv"];
/// What the bytes of a file are, as far as office documents go, or `None` when it is not one (a
/// PDF, or anything else). An encrypted package is a compound file whatever the application: its
@@ -63,6 +70,7 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {
let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
let word_named = ext.as_deref().and_then(|e| WORD_EXTENSIONS.iter().find(|w| **w == e).copied());
let slides_named = ext.as_deref().is_some_and(|e| SLIDE_EXTENSIONS.contains(&e));
+ let sheets_named = ext.as_deref().and_then(|e| SHEET_EXTENSIONS.iter().find(|w| **w == e).copied());
let contains = |needle: &[u8]| bytes.windows(needle.len()).any(|w| w == needle);
if bytes.starts_with(b"PK\x03\x04") {
// a zip package: its part names are plain text in the local headers and the directory
@@ -75,6 +83,18 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {
if contains(b"ppt/presentation.xml") {
return Some(OfficeFile::Slides);
}
+ if contains(b"xl/workbook.xml") {
+ return Some(OfficeFile::Sheets(match sheets_named {
+ Some(e @ ("xlsm" | "xltx" | "xltm")) => e,
+ _ => "xlsx",
+ }));
+ }
+ if contains(b"xl/workbook.bin") {
+ return Some(OfficeFile::Sheets("xlsb"));
+ }
+ if contains(b"application/vnd.oasis.opendocument.spreadsheet") {
+ return Some(OfficeFile::Sheets("ods"));
+ }
if contains(b"application/vnd.oasis.opendocument.text") {
return Some(OfficeFile::Word(if word_named == Some("ott") { "ott" } else { "odt" }));
}
@@ -90,6 +110,9 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {
if slides_named {
return Some(OfficeFile::Slides);
}
+ if let Some(e @ ("xlsx" | "xlsm" | "xltx" | "xltm" | "xlsb")) = sheets_named {
+ return Some(OfficeFile::Sheets(e));
+ }
return word_named.filter(|e| matches!(*e, "docx" | "docm" | "dotx" | "dotm")).map(OfficeFile::Word);
}
return None;
@@ -97,6 +120,12 @@ pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {
if head.starts_with(b"{\\rtf") {
return Some(OfficeFile::Word("rtf"));
}
+ // plain-text tables are known by their name alone
+ if let Some(e @ ("csv" | "tsv")) = sheets_named
+ && !head.contains(&0)
+ {
+ return Some(OfficeFile::Sheets(e));
+ }
None
}
@@ -116,7 +145,9 @@ pub(crate) fn file_at(path: &str) -> Result<Option<(OfficeFile, Vec<u8>)>, Mobil
let mut head = [0u8; 8];
let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut head)).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;
let head = head.get(..n).unwrap_or_default();
- if !(head.starts_with(b"PK\x03\x04") || head.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) || head.starts_with(b"{\\rtf")) {
+ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default();
+ let text_table = ext.eq_ignore_ascii_case("csv") || ext.eq_ignore_ascii_case("tsv");
+ if !(text_table || head.starts_with(b"PK\x03\x04") || head.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) || head.starts_with(b"{\\rtf")) {
return Ok(None);
}
let bytes = read(path)?;
@@ -134,6 +165,7 @@ pub(crate) fn open(
Ok(match kind {
OfficeFile::Word(ext) => Arc::new(crate::word::WordDocument::open(path, ext, bytes, password, locale)?),
OfficeFile::Slides => Arc::new(crate::slides::SlideDeck::open(path, bytes)?),
+ OfficeFile::Sheets(ext) => Arc::new(crate::sheets::SheetBook::open(path, ext, bytes, password)?),
})
}
@@ -185,7 +217,8 @@ mod tests {
assert_eq!(sniff(b"PK\x03\x04....word/document.xml....", "/a/Letter.dotx"), Some(OfficeFile::Word("dotx")));
assert_eq!(sniff(b"PK\x03\x04mimetypeapplication/vnd.oasis.opendocument.text", "/a/x"), Some(OfficeFile::Word("odt")));
assert_eq!(sniff(b"PK\x03\x04....ppt/presentation.xml....", "/a/Deck.pdf"), Some(OfficeFile::Slides));
- assert_eq!(sniff(b"PK\x03\x04xl/workbook.xml", "/a/Book.xlsx"), None);
+ assert_eq!(sniff(b"PK\x03\x04xl/workbook.xml", "/a/Book.pdf"), Some(OfficeFile::Sheets("xlsx")));
+ assert_eq!(sniff(b"a,b\n1,2\n", "/a/t.csv"), Some(OfficeFile::Sheets("csv")));
assert_eq!(sniff(b"{\\rtf1\\ansi hello}", "/a/x.txt"), Some(OfficeFile::Word("rtf")));
assert_eq!(sniff(b"plain words", "/a/notes.docx"), None);
}
@@ -196,7 +229,8 @@ mod tests {
cfb.extend("EncryptedPackage".encode_utf16().flat_map(u16::to_le_bytes));
assert_eq!(sniff(&cfb, "/a/Locked.docx"), Some(OfficeFile::Word("docx")));
assert_eq!(sniff(&cfb, "/a/Locked.pptx"), Some(OfficeFile::Slides));
- assert_eq!(sniff(&cfb, "/a/Locked.xlsx"), None);
+ assert_eq!(sniff(&cfb, "/a/Locked.xlsx"), Some(OfficeFile::Sheets("xlsx")));
+ assert_eq!(sniff(&cfb, "/a/Locked.bin"), None);
}
#[test]
diff --git a/engine/mobile/src/sheets.rs b/engine/mobile/src/sheets.rs
new file mode 100644
index 0000000..34dcf53
--- /dev/null
+++ b/engine/mobile/src/sheets.rs
@@ -0,0 +1,395 @@
+//! Excel workbooks (.xlsx, .xlsb, .ods, .csv) through storytold/gridcraft's engine. A workbook is
+//! not pages: the app draws its sheets as a grid of its own from what [`SheetBook`] serves (the
+//! cells of a window with their looks, column widths and row heights, merges, frozen panes). Its
+//! sheets still count as the document's pages, for titles, Recent and thumbnails.
+
+use std::sync::Arc;
+
+use gridcraft_engine::core::CellRef;
+use gridcraft_engine::model::{BorderLine, BorderStyle, Color, HAlign, PatternType, Sheet, VAlign, Visibility, Workbook};
+use pdfcraft_render::PageText;
+
+use crate::office::OfficeDoc;
+use crate::{DocumentInfo, DocumentKind, LinkInfo, MobileError, PageInfo, RenderedImage, TileRect};
+
+/// Points per pixel at 96 dpi: gridcraft keeps column widths and row heights in such pixels.
+const PT: f32 = 0.75;
+
+/// The most cells one window asks for (a screen holds a few hundred).
+const MAX_WINDOW: u64 = 20_000;
+
+/// A sheet as the grid lays it out.
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct SheetInfo {
+ pub name: String,
+ /// The used area: rows and columns from A1 to its far corner.
+ pub rows: u32,
+ pub cols: u32,
+ /// Frozen rows at the top and columns at the left (0: none).
+ pub frozen_rows: u32,
+ pub frozen_cols: u32,
+ pub gridlines: bool,
+ pub hidden: bool,
+ /// Its tab's colour, `0xRRGGBB`.
+ pub tab_color: Option<u32>,
+}
+
+/// Column widths and row heights of a window, in points (0: hidden).
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct SheetAxes {
+ pub col_widths: Vec<f32>,
+ pub row_heights: Vec<f32>,
+}
+
+/// A border of a cell: its weight (1 thin, 2 medium, 3 thick; 0 none) and colour.
+#[derive(Debug, Clone, Copy, uniffi::Record)]
+pub struct CellEdge {
+ pub weight: u8,
+ pub color: u32,
+}
+
+/// A cell as the grid draws it: the text it shows, in its looks. Colours are `0xRRGGBB`.
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct CellView {
+ pub row: u32,
+ pub col: u32,
+ pub text: String,
+ pub fill: Option<u32>,
+ pub ink: u32,
+ pub bold: bool,
+ pub italic: bool,
+ pub underline: bool,
+ pub strike: bool,
+ /// Font size in points.
+ pub size: f32,
+ /// `l`, `c` or `r` (General: numbers right, text left, as Excel shows them).
+ pub align: String,
+ /// `t`, `c` or `b`.
+ pub valign: String,
+ pub wrap: bool,
+ pub left: CellEdge,
+ pub top: CellEdge,
+ pub right: CellEdge,
+ pub bottom: CellEdge,
+}
+
+/// Merged cells, rows `row0..=row1`, columns `col0..=col1`.
+#[derive(Debug, Clone, Copy, uniffi::Record)]
+pub struct CellSpan {
+ pub row0: u32,
+ pub col0: u32,
+ pub row1: u32,
+ pub col1: u32,
+}
+
+/// One open workbook, its formulas computed.
+pub(crate) struct SheetBook {
+ wb: Arc<Workbook>,
+ name: String,
+ path: String,
+ file_size: u64,
+ encrypted: bool,
+}
+
+fn open_error(e: String) -> MobileError {
+ if e.contains(gridcraft_engine::io::PASSWORD_REQUIRED) {
+ MobileError::NeedsPassword
+ } else if e.contains(gridcraft_engine::io::WRONG_PASSWORD) {
+ MobileError::WrongPassword
+ } else {
+ MobileError::Open(e)
+ }
+}
+
+fn rgb(c: Option<[u8; 3]>) -> Option<u32> {
+ c.map(|[r, g, b]| (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b))
+}
+
+impl SheetBook {
+ pub(crate) fn open(path: &str, ext: &str, bytes: &[u8], password: Option<&str>) -> Result<SheetBook, MobileError> {
+ let name = crate::office::file_name(path);
+ let stem = std::path::Path::new(&name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
+ let encrypted = gridcraft_xlsx::sniff(bytes) == gridcraft_xlsx::Format::Encrypted;
+ let (mut wb, _warnings) =
+ gridcraft_engine::io::open_bytes_with_password(&format!("{stem}.{ext}"), bytes, password).map_err(|e| open_error(e.to_string()))?;
+ // computed as the desktop app does on open: values the file left stale are brought up to date
+ gridcraft_engine::calc::Calc::new().recalc_all(&mut wb);
+ Ok(SheetBook { wb: Arc::new(wb), name, path: path.to_string(), file_size: bytes.len() as u64, encrypted })
+ }
+
+ fn sheet(&self, index: u32) -> Result<&Sheet, MobileError> {
+ let n = self.wb.sheets.len();
+ self.wb
+ .sheets
+ .get(index as usize)
+ .map(|s| &**s)
+ .ok_or_else(|| MobileError::Command(format!("sheet {} is out of range: the workbook has {n} sheets", u64::from(index) + 1)))
+ }
+
+ /// The sheets in tab order.
+ pub(crate) fn sheets(&self) -> Vec<SheetInfo> {
+ self.wb
+ .sheets
+ .iter()
+ .map(|s| {
+ let (rows, cols) = s.used_range().map_or((0, 0), |r| (r.end.row.saturating_add(1), r.end.col.saturating_add(1)));
+ SheetInfo {
+ name: s.name.clone(),
+ rows,
+ cols,
+ frozen_rows: s.freeze.map_or(0, |f| f.0),
+ frozen_cols: s.freeze.map_or(0, |f| f.1),
+ gridlines: s.show_gridlines,
+ hidden: s.visibility != Visibility::Visible,
+ tab_color: s.tab_color.and_then(|c| rgb(c.resolve(&self.wb.theme))),
+ }
+ })
+ .collect()
+ }
+
+ /// Widths of columns `col0..col0+cols` and heights of rows `row0..row0+rows` of sheet `sheet`.
+ pub(crate) fn axes(&self, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<SheetAxes, MobileError> {
+ let s = self.sheet(sheet)?;
+ let cols = cols.min(16_384);
+ let rows = rows.min(1_048_576).min(100_000);
+ Ok(SheetAxes {
+ col_widths: (col0..col0.saturating_add(cols)).map(|c| s.col_width(c) * PT).collect(),
+ row_heights: (row0..row0.saturating_add(rows)).map(|r| s.row_height(r) * PT).collect(),
+ })
+ }
+
+ /// The cells of the window that show something (text, a fill or a border).
+ pub(crate) fn cells(&self, sheet: u32, row0: u32, rows: u32, col0: u32, cols: u32) -> Result<Vec<CellView>, MobileError> {
+ let s = self.sheet(sheet)?;
+ if u64::from(rows) * u64::from(cols) > MAX_WINDOW {
+ return Err(MobileError::Command(format!("a window of {rows} × {cols} cells is too large")));
+ }
+ let wb = &*self.wb;
+ let theme = &wb.theme;
+ let edge = |b: &BorderLine| CellEdge {
+ weight: match b.style {
+ BorderStyle::None => 0,
+ BorderStyle::Medium
+ | BorderStyle::MediumDashed
+ | BorderStyle::MediumDashDot
+ | BorderStyle::MediumDashDotDot
+ | BorderStyle::Double => 2,
+ BorderStyle::Thick => 3,
+ _ => 1,
+ },
+ color: rgb(b.color.resolve(theme)).unwrap_or(0),
+ };
+ let mut out = Vec::new();
+ for row in row0..row0.saturating_add(rows) {
+ for col in col0..col0.saturating_add(cols) {
+ let c = CellRef::new(row, col);
+ let style = wb.styles.get(s.style_id(c));
+ let text = gridcraft_engine::display::cell_text(wb, s, c);
+ let fill = match style.fill.pattern {
+ PatternType::None => None,
+ PatternType::Solid => rgb(style.fill.fg.resolve(theme)),
+ _ => rgb(style.fill.fg.resolve(theme)).or_else(|| rgb(style.fill.bg.resolve(theme))),
+ };
+ let b = &style.borders;
+ if text.is_empty() && fill.is_none() && [&b.left, &b.top, &b.right, &b.bottom].iter().all(|l| l.is_none()) {
+ continue;
+ }
+ let number = matches!(s.value(c), gridcraft_engine::core::Value::Number(_));
+ let align = match style.align.h {
+ HAlign::Center | HAlign::CenterAcross => "c",
+ HAlign::Right => "r",
+ HAlign::General if number => "r",
+ _ => "l",
+ };
+ let valign = match style.align.v {
+ VAlign::Top => "t",
+ VAlign::Center => "c",
+ _ => "b",
+ };
+ let f = &style.font;
+ out.push(CellView {
+ row,
+ col,
+ text,
+ fill,
+ ink: if matches!(f.color, Color::Auto) { 0 } else { rgb(f.color.resolve(theme)).unwrap_or(0) },
+ bold: f.bold,
+ italic: f.italic,
+ underline: f.underline != Default::default(),
+ strike: f.strike,
+ size: if f.size > 0.0 { f.size } else { 11.0 },
+ align: align.into(),
+ valign: valign.into(),
+ wrap: style.align.wrap,
+ left: edge(&b.left),
+ top: edge(&b.top),
+ right: edge(&b.right),
+ bottom: edge(&b.bottom),
+ });
+ }
+ }
+ Ok(out)
+ }
+
+ /// The merged areas of sheet `sheet`.
+ pub(crate) fn merges(&self, sheet: u32) -> Result<Vec<CellSpan>, MobileError> {
+ Ok(self.sheet(sheet)?.merges.iter().map(|m| CellSpan { row0: m.start.row, col0: m.start.col, row1: m.end.row, col1: m.end.col }).collect())
+ }
+
+ /// The cells of sheet `sheet` whose shown text holds `query` (at most `limit`), in reading order.
+ pub(crate) fn find(&self, sheet: u32, query: &str, case_sensitive: bool, limit: u32) -> Result<Vec<CellSpan>, MobileError> {
+ let s = self.sheet(sheet)?;
+ let q = if case_sensitive { query.to_string() } else { query.to_lowercase() };
+ if q.trim().is_empty() {
+ return Ok(Vec::new());
+ }
+ let Some(used) = s.used_range() else { return Ok(Vec::new()) };
+ let mut out = Vec::new();
+ for row in 0..=used.end.row {
+ for col in 0..=used.end.col {
+ let t = gridcraft_engine::display::cell_text(&self.wb, s, CellRef::new(row, col));
+ let hit = if case_sensitive { t.contains(&q) } else { t.to_lowercase().contains(&q) };
+ if hit {
+ out.push(CellSpan { row0: row, col0: col, row1: row, col1: col });
+ if out.len() >= limit as usize {
+ return Ok(out);
+ }
+ }
+ }
+ }
+ Ok(out)
+ }
+
+ /// A sheet's used size in points (at least a screenful of the default grid).
+ fn extent(s: &Sheet) -> (f32, f32) {
+ let (rows, cols) = s.used_range().map_or((20, 8), |r| (r.end.row.saturating_add(1).max(20), r.end.col.saturating_add(1).max(8)));
+ let w: f32 = (0..cols.min(200)).map(|c| s.col_width(c) * PT).sum();
+ let h: f32 = (0..rows.min(2_000)).map(|r| s.row_height(r) * PT).sum();
+ (w.max(1.0), h.max(1.0))
+ }
+}
+
+impl OfficeDoc for SheetBook {
+ fn info(&self, id: u64) -> DocumentInfo {
+ let p = &self.wb;
+ DocumentInfo {
+ id,
+ kind: DocumentKind::Sheets,
+ name: self.name.clone(),
+ path: Some(self.path.clone()),
+ pages: p
+ .sheets
+ .iter()
+ .map(|s| {
+ let (w, h) = Self::extent(s);
+ PageInfo { width: w, height: h, label: s.name.clone(), rotation: 0 }
+ })
+ .collect(),
+ title: None,
+ author: None,
+ subject: None,
+ keywords: None,
+ creator: None,
+ producer: None,
+ pdf_version: String::new(),
+ file_size: self.file_size,
+ encrypted: self.encrypted,
+ tagged: false,
+ read_only_reason: Some("Workbooks open for viewing in this version".into()),
+ allows_printing: true,
+ allows_copying: true,
+ allows_annotation: false,
+ allows_form_filling: false,
+ allows_assembly: false,
+ dirty: false,
+ undo: None,
+ redo: None,
+ fields: 0,
+ has_outline: false,
+ attachments: 0,
+ signed: false,
+ comments_hidden: false,
+ generation: 0,
+ }
+ }
+
+ /// A plain picture of the sheet's top-left: cell fills and grid lines (thumbnails; the app draws
+ /// the real grid itself).
+ fn render_page(&self, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError> {
+ let s = self.sheet(page)?;
+ let (w, h) = Self::extent(s);
+ let scale = scale.clamp(0.01, 4.0);
+ let (full_w, full_h) = (((w * scale).ceil() as u32).clamp(1, 2048), ((h * scale).ceil() as u32).clamp(1, 2048));
+ let t = tile.unwrap_or(TileRect { x: 0, y: 0, width: full_w, height: full_h });
+ let (tw, th) = (t.width.clamp(1, 2048), t.height.clamp(1, 2048));
+ let mut rgba = vec![255u8; (tw as usize) * (th as usize) * 4];
+ let mut put = |x: i64, y: i64, c: u32| {
+ let (x, y) = (x - i64::from(t.x), y - i64::from(t.y));
+ if x < 0 || y < 0 || x >= i64::from(tw) || y >= i64::from(th) {
+ return;
+ }
+ let i = ((y as usize) * (tw as usize) + x as usize) * 4;
+ if let Some(px) = rgba.get_mut(i..i + 4) {
+ px.copy_from_slice(&[(c >> 16) as u8, (c >> 8) as u8, c as u8, 255]);
+ }
+ };
+ let (rows, cols) = s.used_range().map_or((20, 8), |r| (r.end.row.saturating_add(1).clamp(20, 200), r.end.col.saturating_add(1).clamp(8, 60)));
+ let col_x: Vec<f32> = std::iter::once(0.0)
+ .chain((0..cols).scan(0.0, |a, c| {
+ *a += s.col_width(c) * PT;
+ Some(*a)
+ }))
+ .collect();
+ let row_y: Vec<f32> = std::iter::once(0.0)
+ .chain((0..rows).scan(0.0, |a, r| {
+ *a += s.row_height(r) * PT;
+ Some(*a)
+ }))
+ .collect();
+ for cell in self.cells(page, 0, rows, 0, cols)? {
+ let (Some(x0), Some(x1), Some(y0), Some(y1)) =
+ (col_x.get(cell.col as usize), col_x.get(cell.col as usize + 1), row_y.get(cell.row as usize), row_y.get(cell.row as usize + 1))
+ else {
+ continue;
+ };
+ // a cell with text gets a grey bar for its words, a filled one its fill
+ let fill = cell.fill.or((!cell.text.is_empty()).then_some(0x00C8_CDD6));
+ let Some(color) = fill else { continue };
+ let inset = if cell.fill.is_some() { 0.0 } else { (y1 - y0) * 0.3 };
+ for y in ((y0 + inset) * scale) as i64..((y1 - inset) * scale) as i64 {
+ for x in (x0 * scale) as i64..(x1 * scale) as i64 {
+ put(x, y, color);
+ }
+ }
+ }
+ if s.show_gridlines {
+ let line = 0x00E2_E5EA;
+ for x in &col_x {
+ for y in 0..full_h {
+ put((x * scale) as i64, i64::from(y), line);
+ }
+ }
+ for y in &row_y {
+ for x in 0..full_w {
+ put(i64::from(x), (y * scale) as i64, line);
+ }
+ }
+ }
+ Ok(RenderedImage { width: tw, height: th, rgba })
+ }
+
+ fn page_text(&self, _page: u32) -> Result<Arc<PageText>, MobileError> {
+ // the grid has its own search ([`SheetBook::find`])
+ Ok(Arc::new(PageText::default()))
+ }
+
+ fn links(&self, _page: u32) -> Result<Vec<LinkInfo>, MobileError> {
+ Ok(Vec::new())
+ }
+
+ fn release_memory(&self) {}
+
+ fn as_sheets(&self) -> Option<&SheetBook> {
+ Some(self)
+ }
+}
diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rs
index 6c3a101..c541bcf 100644
--- a/engine/mobile/src/tests.rs
+++ b/engine/mobile/src/tests.rs
@@ -566,3 +566,44 @@ fn opens_a_presentation_as_slides() {
assert_eq!(s.text_of(info.id, hits[0].range).unwrap(), "results");
assert_eq!(file_thumbnail(deck_file("Thumb", "T.pptx"), 100).unwrap().width, 100);
}
+
+/// A workbook: `csv` read by GridCraft and written as `name` (.csv as it is, .xlsx by its writer).
+fn book_file(csv: &str, name: &str) -> String {
+ let path = scratch().join(name);
+ let bytes = if name.ends_with(".csv") {
+ csv.as_bytes().to_vec()
+ } else {
+ let (wb, _) = gridcraft_engine::io::open_bytes("t.csv", csv.as_bytes()).unwrap();
+ gridcraft_engine::io::save_bytes(&wb, name).unwrap()
+ };
+ std::fs::write(&path, bytes).unwrap();
+ path.to_string_lossy().into_owned()
+}
+
+#[test]
+fn opens_a_workbook_and_serves_its_cells() {
+ let s = MobileSession::new();
+ for name in ["Prices.xlsx", "Prices.csv"] {
+ let info = s.open(book_file("Fruit,Price\nApples,3\nPears,4.5\n", name), None).unwrap();
+ assert_eq!(info.kind, DocumentKind::Sheets, "{name}");
+ let sheets = s.sheets(info.id).unwrap();
+ assert_eq!(sheets.len(), 1);
+ assert_eq!((sheets[0].rows, sheets[0].cols), (3, 2));
+ let cells = s.sheet_cells(info.id, 0, 0, 10, 0, 5).unwrap();
+ let text = |r: u32, c: u32| cells.iter().find(|x| x.row == r && x.col == c).map(|x| x.text.clone());
+ assert_eq!(text(1, 0).as_deref(), Some("Apples"));
+ assert_eq!(text(2, 1).as_deref(), Some("4.5"));
+ // General: numbers right, text left
+ assert_eq!(cells.iter().find(|x| x.text == "3").map(|x| x.align.as_str()), Some("r"));
+ assert_eq!(cells.iter().find(|x| x.text == "Pears").map(|x| x.align.as_str()), Some("l"));
+ let axes = s.sheet_axes(info.id, 0, 0, 3, 0, 2).unwrap();
+ assert!(axes.col_widths.iter().all(|w| *w > 20.0) && axes.row_heights.iter().all(|h| *h > 8.0), "{axes:?}");
+ let hits = s.sheet_find(info.id, 0, "pear".into(), false, 10).unwrap();
+ assert_eq!(hits.len(), 1);
+ assert_eq!((hits[0].row0, hits[0].col0), (2, 0));
+ assert!(s.sheet_cells(info.id, 0, 0, 1000, 0, 1000).is_err(), "a window too large is refused");
+ assert!(s.render_page(info.id, 0, 0.5, None).is_ok());
+ }
+ let pdf = s.open(blank_pdf(1), None).unwrap();
+ assert!(s.sheets(pdf.id).is_err());
+}