office: fix OOXML test failures, harden xlsx import without native engine
- Commit
a6b9ae6bfb1bb6ea197f8bd8771144f61d72c274- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-13 23:58 UTC (1 month ago)
- Parents
2861ab0
Diff
library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfSerializer.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfSerializer.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfSerializer.ktindex 8bd8029453..b8f16a3ba8 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfSerializer.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/odf/OdfSerializer.kt@@ -328,10 +328,17 @@ object OdfSerializer { if (cell.rowSpan > 1) body.append(""" table:number-rows-spanned="${cell.rowSpan}"""") if (cell.formula != null) body.append(""" table:formula="${esc(cell.formula)}"""") if (cell.validationName != null) body.append(""" table:content-validation-name="${esc(cell.validationName)}"""")- val numeric = cell.numberValue ?: cell.text.toDoubleOrNull()+ // A freshly-typed formula caches its "=…" source as text, which is+ // not a display value: omit the value cache so readers evaluate+ // table:formula instead of showing the raw "=A1" string.+ // (Imported cells carry a real display string and are unaffected.)+ val isUncomputedFormula = cell.formula != null && cell.text.startsWith("=") &&+ cell.numberValue == null+ val numeric = if (isUncomputedFormula) null+ else cell.numberValue ?: cell.text.toDoubleOrNull() if (numeric != null && cell.valueType != "string") { body.append(""" office:value-type="float" office:value="$numeric"""")- } else if (cell.text.isNotEmpty()) {+ } else if (!isUncomputedFormula && cell.text.isNotEmpty()) { body.append(""" office:value-type="string"""") } body.append(">")@@ -342,7 +349,7 @@ object OdfSerializer { for (p in ann.paragraphs) serializeParagraph(body, p, spanStyles, paraStyles, "text:p") body.append("</office:annotation>") }- if (cell.text.isNotEmpty()) body.append("<text:p>${encodeText(cell.text)}</text:p>")+ if (!isUncomputedFormula && cell.text.isNotEmpty()) body.append("<text:p>${encodeText(cell.text)}</text:p>") body.append("</table:table-cell>") } }
office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt b/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.ktindex b3eae273a5..6db4a8f4ff 100644--- a/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/ExcelFormula.kt@@ -1,13 +1,22 @@ package com.vayunmathur.office.odf /**- * Best-effort translator from an Excel A1-style formula to an ODF OpenFormula string+ * Best-effort translator between Excel A1-style formulas and ODF OpenFormula strings * ("of:=…") (Phases C2/X4). Handles cell/range references (incl. sheet-qualified and absolute),- * converts the ',' argument separator to ';', and preserves string literals. Function names are- * passed through unchanged — most common names (SUM/IF/AVERAGE/…) are identical in both dialects.+ * whole-column/whole-row references (`A:A`, `1:1`), converts the ',' argument separator+ * to ';', and preserves string literals. Function names are passed through unchanged —+ * most common names (SUM/IF/AVERAGE/…) are identical in both dialects.+ *+ * Excel limits: [MAX_ROWS] x [MAX_COLS] ([MAX_COL_LETTERS]). Whole-column/row references+ * are expanded to explicit full-span ranges (the same form LibreOffice Calc writes),+ * e.g. `A:A` -> `[.A1:.A1048576]`. */ internal object ExcelFormula { + const val MAX_ROWS = 1048576+ const val MAX_COLS = 16384+ val MAX_COL_LETTERS: String = indexToCol(MAX_COLS - 1)+ private val REF = Regex( "(?<![A-Za-z0-9_.$])" + "(?:('[^']+'|[A-Za-z_][A-Za-z0-9_.]*)!)?" +@@ -15,11 +24,28 @@ internal object ExcelFormula { "(?![A-Za-z0-9_(])" ) + // Whole-column (`A:A`, `$B:$D`, `Sheet1!A:C`) and whole-row (`1:3`) references.+ // Must run before [REF]: REF cannot match these (it requires row digits on both sides).+ private val WHOLE_COL = Regex(+ "(?<![A-Za-z0-9_.$'])" ++ "(?:('[^']+'|[A-Za-z_][A-Za-z0-9_.]*)!)?" ++ "(\\$?[A-Za-z]{1,3}):(\\$?[A-Za-z]{1,3})" ++ "(?![A-Za-z0-9_(])"+ )+ private val WHOLE_ROW = Regex(+ "(?<![A-Za-z0-9_.$'])" ++ "(?:('[^']+'|[A-Za-z_][A-Za-z0-9_.]*)!)?" ++ "(\\$?[0-9]+):(\\$?[0-9]+)" ++ "(?![A-Za-z0-9_(])"+ )+ // A relative/absolute A1 cell reference (col letters + row), used by [shift].+ // The trailing `!` exclusion keeps sheet qualifiers (`S2!A1`) from being shifted+ // as if the sheet name were a cell. private val CELL = Regex( "(?<![A-Za-z0-9_$])" + "(\\$?)([A-Za-z]{1,3})(\\$?)([0-9]+)" +- "(?![A-Za-z0-9_(])"+ "(?![A-Za-z0-9_(!])" ) private const val REF_SHEET = 1 private const val REF_COL = 2@@ -116,7 +142,15 @@ internal object ExcelFormula { } private fun convertSegment(seg: String): String {- val refWrapped = REF.replace(seg) { m ->+ val wholeCols = WHOLE_COL.replace(seg) { m ->+ val sheet = m.groupValues[1]+ wrapWholeCol(sheet, m.groupValues[2], m.groupValues[3])+ }+ val wholeRows = WHOLE_ROW.replace(wholeCols) { m ->+ val sheet = m.groupValues[1]+ wrapWholeRow(sheet, m.groupValues[2], m.groupValues[3])+ }+ val refWrapped = REF.replace(wholeRows) { m -> val sheet = m.groupValues[1] val ref = m.groupValues[2] wrap(sheet, ref)@@ -124,6 +158,136 @@ internal object ExcelFormula { return refWrapped.replace(',', ';') } + /** `A:C` -> `[.$A$1:.$C$1048576]`-style full-span range (absolute parts preserved). */+ private fun wrapWholeCol(sheet: String, a: String, b: String): String {+ val (ca, absA) = splitAbs(a)+ val (cb, absB) = splitAbs(b)+ val colA = (if (absA) "$" else "") + ca+ val colB = (if (absB) "$" else "") + cb+ val pre = prefixSheet(sheet)+ return "[$pre$colA" + "1:.$colB$MAX_ROWS]"+ }++ /** `2:5` -> `[.A2:.XFD5]`. */+ private fun wrapWholeRow(sheet: String, a: String, b: String): String {+ val (ra, absA) = splitAbs(a)+ val (rb, absB) = splitAbs(b)+ val pre = prefixSheet(sheet)+ val r1 = "$pre${if (absA) "$" else ""}A${ra.trimStart('$')}"+ val r2 = ".${if (absB) "$" else ""}$MAX_COL_LETTERS${rb.trimStart('$')}"+ return "[$r1:$r2]"+ }++ private fun splitAbs(s: String): Pair<String, Boolean> =+ if (s.startsWith("$")) s.substring(1) to true else s to false++ private val ODF_REF = Regex("\\[([^\\]]*)]")++ /** Returns an Excel-style formula ("=…") for the given OpenFormula ("of:=…"). */+ fun fromOdf(of: String): String {+ var body = of.trim()+ if (body.startsWith("of:", ignoreCase = true)) body = body.substring(3)+ body = body.trim().removePrefix("=")+ val sb = StringBuilder("=")+ var i = 0+ while (i < body.length) {+ val c = body[i]+ if (c == '"') {+ // Copy string literals verbatim ("" is an escaped quote).+ var j = i + 1+ while (j < body.length && !isStringEnd(body, j)) {+ j = if (isEscapedQuote(body, j)) j + 2 else j + 1+ }+ val end = if (j < body.length) j else body.length - 1+ sb.append(body, i, minOf(end + 1, body.length))+ i = end + 1+ } else {+ val nextQuote = body.indexOf('"', i).let { if (it < 0) body.length else it }+ sb.append(fromOdfSegment(body.substring(i, nextQuote)))+ i = nextQuote+ }+ }+ return sb.toString()+ }++ private fun fromOdfSegment(seg: String): String {+ val refConverted = ODF_REF.replace(seg) { m -> convertOdfRef(m.groupValues[1]) }+ return refConverted.replace(';', ',')+ }++ /** Converts one OpenFormula bracket body ("$Sheet.A1", ".A1", "$A$1") back to Excel A1. */+ private fun convertOdfRef(inner: String): String {+ val parts = inner.split(":")+ if (parts.size == 2) {+ // Full-span ranges (from whole-column/row refs) collapse back to `A:A` / `2:5`.+ wholeColOf(parts)?.let { return it }+ wholeRowOf(parts)?.let { return it }+ }+ return parts.joinToString(":") { convertOdfRefPart(it) }+ }++ private fun wholeColOf(parts: List<String>): String? {+ val a = splitEndpoint(parts[0]) ?: return null+ val b = splitEndpoint(parts[1]) ?: return null+ if (a.row != "1" || b.row != MAX_ROWS.toString()) return null+ if (a.rowAbs || b.rowAbs) return null+ if (a.sheetNorm != b.sheetNorm) return null+ return "${a.sheetPrefix}${a.colAbs}${a.col}:${b.col}"+ }++ private fun wholeRowOf(parts: List<String>): String? {+ val a = splitEndpoint(parts[0]) ?: return null+ val b = splitEndpoint(parts[1]) ?: return null+ if (a.col.uppercase() != "A" || b.col.uppercase() != MAX_COL_LETTERS) return null+ if (a.colAbs.isNotEmpty() || b.colAbs.isNotEmpty()) return null+ if (a.sheetNorm != b.sheetNorm) return null+ return if (a.sheet.isEmpty()) "${a.row}:${b.row}" else "${a.sheetPrefix}${a.row}:${b.row}"+ }++ private data class Endpoint(+ val sheet: String, val sheetPrefix: String, val sheetNorm: String,+ val col: String, val colAbs: String, val row: String, val rowAbs: Boolean,+ )++ private fun splitEndpoint(part: String): Endpoint? {+ val p = part.trim().removePrefix("$")+ val sheet: String+ val sheetPrefix: String+ val cell: String+ if (p.startsWith(".")) {+ sheet = ""; sheetPrefix = ""; cell = p.substring(1)+ } else if (p.contains(".")) {+ sheet = p.substringBefore(".").trim('\'')+ cell = p.substringAfter(".")+ val q = if (sheet.all { it.isLetterOrDigit() || it == '_' }) sheet else "'$sheet'"+ sheetPrefix = "$q!"+ } else return null+ val m = Regex("^(\\$?)([A-Za-z]{1,3})(\\$?)([0-9]+)$").matchEntire(cell.trim()) ?: return null+ return Endpoint(+ sheet, sheetPrefix, sheet.lowercase(),+ m.groupValues[2], m.groupValues[1], m.groupValues[4],+ m.groupValues[3] == "$")+ }++ private val CELL_TOKEN = Regex("^(\\$?)([A-Za-z]{1,3})(\\$?)([0-9]+)$")++ private fun convertOdfRefPart(part: String): String {+ val p = part.trim()+ // Same-sheet refs: ".A1" / ".$A$1".+ if (p.startsWith(".")) return p.substring(1)+ // Dotless absolute from other producers: "[$A$1]" stays "$A$1".+ if (!p.contains(".") && CELL_TOKEN.matches(p)) return p+ // Sheet-qualified: "$Sheet.A1" / "$'My Sheet'.$A$1".+ var q = p+ if (q.startsWith("$")) q = q.substring(1)+ val dot = q.indexOf('.')+ if (dot < 0) return q // Not a ref after all; pass through.+ val sheet = q.substring(0, dot).trim('\'')+ val cell = q.substring(dot + 1)+ val s = if (sheet.all { it.isLetterOrDigit() || it == '_' }) sheet else "'$sheet'"+ return "$s!$cell"+ }+ private fun wrap(sheet: String, ref: String): String { return if (ref.contains(':')) { val (a, b) = ref.split(':', limit = 2)
office/src/main/java/com/vayunmathur/office/odf/OoxmlImporter.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlImporter.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlImporter.ktindex 1878b95e54..79464ce3c9 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlImporter.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlImporter.kt@@ -1,5 +1,6 @@ package com.vayunmathur.office.odf +import com.vayunmathur.library.log.Log import com.vayunmathur.library.ui.odf.OdfDocument /**@@ -36,6 +37,9 @@ object OoxmlImporter { resolveDocKind(ext, pkg, fileName) }.getOrElse { // Best-effort: never crash the app on a malformed but recognized package.+ // Dev-gated so JVM unit tests (Android stubs) stay silent-safe; on a dev+ // device this surfaces the swallowed cause for the next malformed file.+ Log.dev(TAG, "best-effort fallback for $fileName", it) fallbackDoc(ext, pkg, fileName) } }@@ -89,4 +93,6 @@ object OoxmlImporter { private val DOCX_EXTS = setOf("docx", "docm", "dotx", "dotm") private val XLSX_EXTS = setOf("xlsx", "xlsm", "xltx", "xltm") private val PPTX_EXTS = setOf("pptx", "pptm", "potx", "potm", "ppsx", "ppsm")++ private const val TAG = "OoxmlImporter" }
office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt
diff --git a/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt b/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.ktindex 7e43aaef2f..9199a98835 100644--- a/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt+++ b/office/src/main/java/com/vayunmathur/office/odf/OoxmlXlsx.kt@@ -23,6 +23,11 @@ import org.xmlpull.v1.XmlPullParser */ internal object OoxmlXlsx { + private const val EXCEL_EPOCH_OFFSET_DAYS = 25569 // days between 1899-12-30 and 1970-01-01+ private const val MILLIS_PER_DAY = 86400_000L+ private const val MAX_EXCEL_SERIAL = 2958465.0 // 9999-12-31+ private const val DEFAULT_SCIENTIFIC_DECIMALS = 2+ fun import(pkg: OoxmlPackage, fileName: String): OdfDocument.Spreadsheet { val theme = OoxmlTheme.parse(pkg.entries["xl/theme/theme1.xml"]) val shared = pkg.entries["xl/sharedStrings.xml"]?.let { parseSharedStrings(it) } ?: emptyList()@@ -447,7 +452,7 @@ internal object OoxmlXlsx { // formatted per the number format so dates/percent/currency don't show as bare numbers. val fmtForDisplay = resolvedFmt ?: if (base.valueType == "date") OdfNumberFormat(isDate = true) else null val displayText = if (base.numberValue != null && base.valueType != "boolean" && fmtForDisplay != null)- OfficeNative.formatValue(base.numberValue!!, fmtForDisplay) else base.text+ formatDisplayValue(base.numberValue!!, fmtForDisplay, base.text) else base.text return base.copy( text = displayText, formula = formula ?: base.formula,@@ -465,6 +470,52 @@ internal object OoxmlXlsx { ) } + /**+ * Display string for a numeric cell. Prefers the native formatter (exact Excel rendering),+ * but a cosmetic string must never fail the whole import: when the engine can't load+ * (JVM unit tests, or a device-side load failure) a pure-Kotlin best-effort applies.+ */+ private fun formatDisplayValue(value: Double, fmt: OdfNumberFormat, raw: String): String {+ runCatching { return OfficeNative.formatValue(value, fmt) }+ return kotlinFormat(value, fmt, raw)+ }++ /** Best-effort number/date rendering without the native engine. */+ private fun kotlinFormat(value: Double, fmt: OdfNumberFormat, raw: String): String {+ if (fmt.isDate || fmt.isTime) return excelSerialToIso(value) ?: raw+ if (fmt.isScientific) return "%.${fmt.decimals ?: DEFAULT_SCIENTIFIC_DECIMALS}E".format(java.util.Locale.ROOT, value)+ if (fmt.isFraction) return raw+ val scaled = if (fmt.percent) value * 100 else value+ val decimals = fmt.decimals ?: 0+ var s = if (decimals > 0) "%.${decimals}f".format(java.util.Locale.ROOT, scaled)+ else kotlin.math.round(scaled).toLong().toString()+ if (fmt.grouping) s = groupThousands(s)+ if (fmt.percent) s += "%"+ fmt.currencySymbol?.let { s = "$it$s" }+ return s+ }++ private fun groupThousands(s: String): String {+ val neg = s.startsWith("-")+ val body = if (neg) s.substring(1) else s+ val dot = body.indexOf('.')+ val int = if (dot >= 0) body.substring(0, dot) else body+ val frac = if (dot >= 0) body.substring(dot) else ""+ val grouped = int.reversed().chunked(3).joinToString(",").reversed()+ return (if (neg) "-" else "") + grouped + frac+ }++ /** Excel serial (days since 1899-12-30) to "yyyy-mm-dd" (with time when fractional). */+ private fun excelSerialToIso(serial: Double): String? {+ if (serial < 0 || serial > MAX_EXCEL_SERIAL) return null+ val millis = ((serial - EXCEL_EPOCH_OFFSET_DAYS) * MILLIS_PER_DAY).toLong()+ val cal = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"))+ cal.timeInMillis = millis+ fun p(field: Int, digits: Int = 2) = cal.get(field).toString().padStart(digits, '0')+ val date = "${p(java.util.Calendar.YEAR, 4)}-${(cal.get(java.util.Calendar.MONTH) + 1).toString().padStart(2, '0')}-${p(java.util.Calendar.DAY_OF_MONTH)}"+ return if (serial % 1 != 0.0) "$date ${p(java.util.Calendar.HOUR_OF_DAY)}:${p(java.util.Calendar.MINUTE)}" else date+ }+ /** Raw cell content (value/inline/formula). */ private class CellContent( var value: String? = null,
office/src/main/java/com/vayunmathur/office/ui/SpreadsheetSections.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetSections.kt b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetSections.ktindex c3bec4c9f1..f6f0e16d17 100644--- a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetSections.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetSections.kt@@ -29,6 +29,7 @@ import com.vayunmathur.library.ui.TextField import com.vayunmathur.library.ui.TextFieldDefaults import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.office.R+import com.vayunmathur.office.odf.ExcelFormula /** Cell edit bar above the grid: address label, formula field, done. State lives in [SpreadsheetView]. */ @Composable@@ -52,7 +53,9 @@ internal fun SpreadsheetEditBar( if (r + 1 < rowCount) { onCellSelected(si, r + 1, c) val nextText =- doc.sheets[si].rows.getOrNull(r + 1)?.cells?.getOrNull(c)?.let { it.formula ?: it.text } ?: ""+ doc.sheets[si].rows.getOrNull(r + 1)?.cells?.getOrNull(c)?.let {+ it.formula?.let { f -> try { ExcelFormula.fromOdf(f) } catch (_: Exception) { f } } ?: it.text+ } ?: "" onAdvanceCell(Triple(si, r + 1, c), TextFieldValue(nextText, TextRange(0, nextText.length))) } else { onAdvanceCell(null, null); onCellSelected(si, -1, -1) } }
office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.ktindex 710d03ebc8..a31814c71f 100644--- a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetValues.kt@@ -4,6 +4,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfNamedRange import com.vayunmathur.office.util.OfficeNative /**@@ -18,7 +19,9 @@ interface SpreadsheetValues { @Composable fun rememberNativeSpreadsheetValues(doc: OdfDocument.Spreadsheet): SpreadsheetValues {- val handle = remember(doc) { OfficeNative.createWorkbook(doc.sheets, System.currentTimeMillis()) }+ val handle = remember(doc) {+ OfficeNative.createWorkbook(doc.sheets, System.currentTimeMillis(), doc.namedRanges)+ } DisposableEffect(doc) { onDispose { OfficeNative.nativeFree(handle) } } return remember(handle) { object : SpreadsheetValues {
office/src/main/java/com/vayunmathur/office/ui/SpreadsheetViews.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetViews.kt b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetViews.ktindex 50ed020d3e..8f16db9903 100644--- a/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/SpreadsheetViews.kt@@ -48,6 +48,7 @@ import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.odf.OdfBorders import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.office.R+import com.vayunmathur.office.odf.ExcelFormula import com.vayunmathur.office.util.OfficeNative @Composable@@ -229,7 +230,7 @@ fun SpreadsheetView( sw) } } else Modifier) .then(if (isMatch) Modifier.background(Color(0xFFFFEB3B).copy(alpha = 0.3f)) else effBg?.let { Modifier.background(Color(it.toInt())) } ?: Modifier)- .then(if (isEditMode) Modifier.clickable { editingCell = Triple(selectedSheet, rowIdx, cellIdx); selectedFloating = -1; onCellSelected(selectedSheet, rowIdx, cellIdx); val t = cell.formula ?: cell.text; editText = TextFieldValue(t, TextRange(0, t.length)) } else Modifier)+ .then(if (isEditMode) Modifier.clickable { editingCell = Triple(selectedSheet, rowIdx, cellIdx); selectedFloating = -1; onCellSelected(selectedSheet, rowIdx, cellIdx); val t = cell.formula?.let { try { ExcelFormula.fromOdf(it) } catch (_: Exception) { it } } ?: cell.text; editText = TextFieldValue(t, TextRange(0, t.length)) } else Modifier) .then(if (cell.annotation != null) Modifier.drawBehind { // Red corner triangle marks a cell comment. (Round 3) val s = 7.dp.toPx()
office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeNative.ktindex aa42292aad..7b38bb2a14 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt@@ -1,5 +1,6 @@ package com.vayunmathur.office.util +import com.vayunmathur.library.ui.odf.OdfNamedRange import com.vayunmathur.library.ui.odf.OdfNumberFormat import com.vayunmathur.library.ui.odf.OdfSheet import kotlinx.serialization.Serializable@@ -89,15 +90,18 @@ object OfficeNative { * Convenience: serialize [sheets] and create a native workbook handle, or * return 0 if the native lib is unavailable or creation fails. */- fun createWorkbook(sheets: List<OdfSheet>, nowMillis: Long = System.currentTimeMillis()): Long =- nativeCreateWorkbook(buildWorkbookJson(sheets), nowMillis)+ fun createWorkbook(+ sheets: List<OdfSheet>,+ nowMillis: Long = System.currentTimeMillis(),+ namedRanges: List<OdfNamedRange> = emptyList(),+ ): Long = nativeCreateWorkbook(buildWorkbookJson(sheets, namedRanges), nowMillis) // ---- Workbook serialization (must agree with the serde schema in formula.rs) ---- private val json = Json { encodeDefaults = true; explicitNulls = false } /** Serializes all [sheets] (name + 2D cell grid) to the compact JSON the Rust engine parses. */- fun buildWorkbookJson(sheets: List<OdfSheet>): String {+ fun buildWorkbookJson(sheets: List<OdfSheet>, namedRanges: List<OdfNamedRange> = emptyList()): String { val dto = WbDto(sheets.map { s -> SheetDto(s.name, s.rows.map { r -> RowDto(r.cells.map { c ->@@ -111,7 +115,7 @@ object OfficeNative { ) }) })- })+ }, namedRanges.map { NrDto(it.name, it.cellRangeAddress) }) return json.encodeToString(dto) } @@ -129,9 +133,13 @@ object OfficeNative { dateTimeTokens = nf.dateTimeTokens.map { t -> TokDto(t.kind, t.style, t.text, t.textual) } ) - @Serializable private data class WbDto(val sheets: List<SheetDto>)+ @Serializable private data class WbDto(+ val sheets: List<SheetDto>,+ val namedRanges: List<NrDto> = emptyList(),+ ) @Serializable private data class SheetDto(val name: String, val rows: List<RowDto>) @Serializable private data class RowDto(val cells: List<CellDto>)+ @Serializable private data class NrDto(val name: String, val addr: String) @Serializable private data class CellDto( val text: String,
office/src/main/java/com/vayunmathur/office/util/OfficeViewModelSheet.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModelSheet.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModelSheet.ktindex 25c9d67769..ff52b2b0d9 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModelSheet.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModelSheet.kt@@ -15,6 +15,7 @@ import com.vayunmathur.library.ui.odf.OdfRow import com.vayunmathur.library.ui.odf.OdfSheet import com.vayunmathur.library.util.AppMessages import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.office.odf.ExcelFormula import com.vayunmathur.office.R import kotlin.io.encoding.Base64 import kotlinx.coroutines.Dispatchers@@ -41,19 +42,44 @@ fun OfficeViewModel.updateCellText(sheetIndex: Int, rowIndex: Int, cellIndex: In val row = rows.getOrNull(rowIndex) ?: return val cells = row.cells.toMutableList() if (cellIndex !in cells.indices) return- cells[cellIndex] = if (newText.startsWith("=")) {+ // A leading apostrophe forces literal text (Excel escape): "'=A1" stores "=A1"+ // as text, and a lone "'" stores an empty string.+ val literal = newText.startsWith("'") && newText.length > 1+ val text = if (newText == "'") "" else if (literal) newText.substring(1) else newText+ cells[cellIndex] = if (!literal && text.startsWith("=")) { // Typed formula (H49): store as OpenFormula, drop cached numeric value.- cells[cellIndex].copy(text = newText, formula = newText, valueType = "float", numberValue = null)+ // The Rust engine only understands bracketed refs ("of:=[.A1]"), so translate+ // Excel A1 ("=A1") via ExcelFormula — otherwise a bare "A1" parses as a+ // function/constant name and evaluates to #NAME?.+ val body = text.trim().removePrefix("=").trim()+ val formula = if (body.startsWith("of:", ignoreCase = true)) body+ else ExcelFormula.toOdf(text)+ // String-producing formulas (starting with a quote, or text functions) get+ // valueType "string" so alignment/formatting treats them as text.+ val stringFormula = body.startsWith("\"") || STRING_RESULT_FUNCS.any {+ body.startsWith(it, ignoreCase = true)+ }+ cells[cellIndex].copy(+ text = text, formula = formula,+ valueType = if (stringFormula) "string" else "float", numberValue = null) } else {- cells[cellIndex].copy(text = newText, formula = null,- valueType = if (newText.toDoubleOrNull() != null) "float" else "string",- numberValue = newText.toDoubleOrNull())+ cells[cellIndex].copy(text = text, formula = null,+ valueType = if (text.toDoubleOrNull() != null) "float" else "string",+ numberValue = text.toDoubleOrNull()) } rows[rowIndex] = OdfRow(cells) sheets[sheetIndex] = sheet.copy(rows = rows) updateDocument(doc.copy(sheets = sheets)) } +/** Functions whose results are (almost) always text, used to type new formulas. */+private val STRING_RESULT_FUNCS = listOf(+ "CONCATENATE(", "CONCAT(", "TEXTJOIN(", "UPPER(", "LOWER(", "PROPER(",+ "LEFT(", "RIGHT(", "MID(", "TRIM(", "CLEAN(", "TEXT(", "REPT(",+ "CHAR(", "UNICHAR(", "SUBSTITUTE(", "REPLACE(",+ "TEXTBEFORE(", "TEXTAFTER(", "ADDRESS(", "HYPERLINK(",+)+ fun OfficeViewModel.addRow(sheetIndex: Int, afterRowIndex: Int) { val doc = (state.value as? OfficeViewModel.ViewState.Loaded)?.document as? OdfDocument.Spreadsheet ?: return val sheets = doc.sheets.toMutableList()@@ -199,12 +225,28 @@ fun OfficeViewModel.fillDown(sheetIndex: Int, srcRow: Int, col: Int, toRow: Int) val row = rows.getOrNull(r) if (row != null && col in row.cells.indices) { val cells = row.cells.toMutableList()- cells[col] = cells[col].copy(- text = src.text, formula = src.formula, valueType = src.valueType,- numberValue = src.numberValue, numberFormat = src.numberFormat,- bold = src.bold, italic = src.italic, textColor = src.textColor,- backgroundColor = src.backgroundColor, alignment = src.alignment- )+ val srcFormula = src.formula+ if (srcFormula != null) {+ // Shift relative refs like Excel: =A1 filled one row down becomes =A2.+ // The stored formula is OpenFormula; convert to Excel, shift, convert back,+ // and refresh the display text to the Excel form.+ val excelSrc = try { ExcelFormula.fromOdf(srcFormula) } catch (_: Exception) { srcFormula }+ val shifted = ExcelFormula.shift(excelSrc, r - srcRow, 0)+ val odf = try { ExcelFormula.toOdf(shifted) } catch (_: Exception) { srcFormula }+ cells[col] = cells[col].copy(+ text = shifted, formula = odf, valueType = src.valueType,+ numberValue = null, numberFormat = src.numberFormat,+ bold = src.bold, italic = src.italic, textColor = src.textColor,+ backgroundColor = src.backgroundColor, alignment = src.alignment+ )+ } else {+ cells[col] = cells[col].copy(+ text = src.text, formula = null, valueType = src.valueType,+ numberValue = src.numberValue, numberFormat = src.numberFormat,+ bold = src.bold, italic = src.italic, textColor = src.textColor,+ backgroundColor = src.backgroundColor, alignment = src.alignment+ )+ } rows[r] = OdfRow(cells) } }
office/src/main/rust/src/formula.rs
diff --git a/office/src/main/rust/src/formula.rs b/office/src/main/rust/src/formula.rsindex 9dab16af0e..598ee89672 100644--- a/office/src/main/rust/src/formula.rs+++ b/office/src/main/rust/src/formula.rs@@ -22,6 +22,16 @@ const EPOCH_OFFSET_DAYS: i64 = 25569; #[derive(Deserialize)] struct WorkbookJson { sheets: Vec<SheetJson>,+ #[serde(default, rename = "namedRanges")]+ named_ranges: Vec<NamedRangeJson>,+}++#[derive(Deserialize)]+struct NamedRangeJson {+ #[serde(default)]+ name: String,+ #[serde(default)]+ addr: String, } #[derive(Deserialize)]@@ -102,6 +112,8 @@ struct Sheet { pub struct Workbook { sheets: Vec<Sheet>, name_to_idx: HashMap<String, usize>,+ /// Named ranges, keyed case-insensitively (uppercase name -> parsed Ref).+ named: HashMap<String, Ref>, now_millis: i64, rng: RefCell<u64>, }@@ -115,6 +127,17 @@ enum Value { Bool(bool), Err(String), Blank,+ /// A spilled-array result (FILTER/SORT/UNIQUE/SEQUENCE/OFFSET with height-width,+ /// or a formula cell whose own result is an array). Scalar contexts use implicit+ /// intersection (the first element); aggregations expand all elements.+ Arr(Vec<Value>),+}++impl Value {+ /// Implicit intersection: the scalar a bare array contributes in scalar context.+ fn first_of(arr: &[Value]) -> Value {+ arr.first().cloned().unwrap_or(Value::Blank)+ } } #[derive(Clone, Debug)]@@ -164,11 +187,22 @@ impl Workbook { let rows: Vec<Vec<Cell>> = s.rows.into_iter().map(|r| r.cells).collect(); sheets.push(Sheet { name: s.name, rows }); }+ let mut named = HashMap::new();+ for nr in parsed.named_ranges {+ let key = nr.name.trim().to_uppercase();+ if key.is_empty() || named.contains_key(&key) {+ continue;+ }+ if let Some(r) = parse_odf_address(&nr.addr, &sheets, &name_to_idx) {+ named.insert(key, r);+ }+ } // Seed the PRNG deterministically from now_millis (splitmix64-style). let seed = (now_millis as u64) ^ 0x9E3779B97F4A7C15; Some(Workbook { sheets, name_to_idx,+ named, now_millis, rng: RefCell::new(seed.max(1)), })@@ -213,6 +247,8 @@ impl Workbook { Value::Str(s) => s, Value::Err(code) => code, Value::Blank => String::new(),+ // Spilled arrays display their top-left (implicit intersection) value.+ Value::Arr(vs) => display_scalar(&Value::first_of(&vs), cell.number_format.as_ref()), } } @@ -450,4 +486,7 @@ include!("formula_part6.rs"); include!("formula_part7.rs"); include!("formula_part8.rs"); include!("formula_part9.rs");-include!("formula_part10.rs");\ No newline at end of file+include!("formula_part10.rs");+include!("formula_part11.rs");+include!("formula_part12.rs");+include!("formula_part13.rs");\ No newline at end of file
office/src/main/rust/src/formula_part10.rs
diff --git a/office/src/main/rust/src/formula_part10.rs b/office/src/main/rust/src/formula_part10.rsindex c7079bd7e8..acba5496e3 100644--- a/office/src/main/rust/src/formula_part10.rs+++ b/office/src/main/rust/src/formula_part10.rs@@ -128,6 +128,106 @@ mod tests { assert_eq!(eval("of:=SQRT(-1)"), "#ERR"); // NaN -> #ERR } + #[test]+ fn named_ranges() {+ // Named range MyRange -> Sheet1.A1:A3, single cell MyCell -> Sheet1.B2.+ // The probe formula lives in D1 (outside the ranges) to avoid self-reference.+ let at = |f: &str| {+ let wjson = format!(+ "{{\"sheets\":[{{\"name\":\"Sheet1\",\"rows\":[\+ {{\"cells\":[{{\"text\":\"1\",\"numberValue\":1}},{{\"text\":\"10\",\"numberValue\":10}},{{\"text\":\"\"}},{{\"text\":\"\",\"formula\":\"{}\"}}]}},\+ {{\"cells\":[{{\"text\":\"2\",\"numberValue\":2}},{{\"text\":\"20\",\"numberValue\":20}}]}},\+ {{\"cells\":[{{\"text\":\"3\",\"numberValue\":3}},{{\"text\":\"30\",\"numberValue\":30}}]}}\+ ]}}],\"namedRanges\":[\+ {{\"name\":\"MyRange\",\"addr\":\"Sheet1.A1:Sheet1.A3\"}},\+ {{\"name\":\"MyCell\",\"addr\":\"Sheet1.B2\"}}\+ ]}}",+ f.replace('"', "\\\"")+ );+ Workbook::from_json(&wjson, 1_700_000_000_000)+ .unwrap()+ .display_value(0, 0, 3)+ };+ // Bare names resolve (scalar + range forms).+ assert_eq!(at("MyRange"), "1");+ assert_eq!(at("of:=SUM(MyRange)"), "6");+ assert_eq!(at("of:=MyCell+1"), "21");+ assert_eq!(at("of:=AVERAGE(MyRange)"), "2");+ // Case-insensitive.+ assert_eq!(at("of:=SUM(myrange)"), "6");+ // Unknown names still #NAME?.+ assert_eq!(at("of:=SUM(Nope)"), "#NAME?");+ // A name must be bare: `MyRange(` is a (missing) function call.+ assert_eq!(at("of:=MyRange(1)"), "#NAME?");+ }++ #[test]+ fn whole_span_ranges() {+ // Full-span expansions (from Excel whole-column/row refs) evaluate over data.+ // Column span excludes the probe cell's column, so no self-reference cycle.+ assert_eq!(eval("of:=SUM([.A1:.A1048576])"), "6");+ // Row span: probe formula in A4 sums rows 1..3 across A..XFD (49k cells,+ // mostly blank). 1+10+2+20+3+30 = 66.+ let wjson = "{\"sheets\":[{\"name\":\"Sheet1\",\"rows\":[\+ {\"cells\":[{\"text\":\"1\",\"numberValue\":1},{\"text\":\"10\",\"numberValue\":10}]},\+ {\"cells\":[{\"text\":\"2\",\"numberValue\":2},{\"text\":\"20\",\"numberValue\":20}]},\+ {\"cells\":[{\"text\":\"3\",\"numberValue\":3},{\"text\":\"30\",\"numberValue\":30}]},\+ {\"cells\":[{\"text\":\"\",\"formula\":\"of:=SUM([.A1:.XFD3])\"}]}\+ ]}]}";+ let wb = Workbook::from_json(wjson, 1_700_000_000_000).unwrap();+ assert_eq!(wb.display_value(0, 3, 0), "66");+ }++ #[test]+ fn xlookup() {+ // Keys A1..A3 = 1,2,3 ; values B1..B3 = 10,20,30.+ assert_eq!(eval("of:=XLOOKUP(2;[.A1:.A3];[.B1:.B3])"), "20");+ assert_eq!(eval("of:=XLOOKUP(9;[.A1:.A3];[.B1:.B3])"), "#N/A");+ assert_eq!(eval("of:=XLOOKUP(9;[.A1:.A3];[.B1:.B3];\"nf\")"), "nf");+ // Exact-or-next-smaller: 2.5 -> key 2 -> 20.+ assert_eq!(eval("of:=XLOOKUP(2.5;[.A1:.A3];[.B1:.B3];;-1)"), "20");+ // Exact-or-next-larger: 2.5 -> key 3 -> 30.+ assert_eq!(eval("of:=XLOOKUP(2.5;[.A1:.A3];[.B1:.B3];;1)"), "30");+ // Last-to-first: duplicate keys would pick the later one; here sanity.+ assert_eq!(eval("of:=XLOOKUP(2;[.A1:.A3];[.B1:.B3];;;-1)"), "20");+ // Binary search on the sorted keys.+ assert_eq!(eval("of:=XLOOKUP(3;[.A1:.A3];[.B1:.B3];;;2)"), "30");+ assert_eq!(eval("of:=XLOOKUP(9;[.A1:.A3];[.B1:.B3];;0;2)"), "#N/A");+ }++ #[test]+ fn dynamic_arrays() {+ // FILTER: B > 15 keeps rows 2,3 -> values 2,3 (first displays).+ assert_eq!(eval("of:=FILTER([.A1:.A3];[.B1:.B3]>15)"), "2");+ assert_eq!(eval("of:=SUM(FILTER([.A1:.A3];[.B1:.B3]>15))"), "5");+ assert_eq!(eval("of:=COUNT(FILTER([.A1:.A3];[.B1:.B3]>15))"), "2");+ assert_eq!(eval("of:=FILTER([.A1:.A3];[.B1:.B3]>99)"), "#CALC!");+ assert_eq!(eval("of:=FILTER([.A1:.A3];[.B1:.B3]>99;\"none\")"), "none");+ // SORT / SORTBY / UNIQUE.+ assert_eq!(eval("of:=SUM(SORT([.B1:.B3];1;-1))"), "60");+ assert_eq!(eval("of:=SORT([.B1:.B3];1;-1)"), "30");+ assert_eq!(eval("of:=SUM(SORTBY([.A1:.A3];[.B1:.B3];-1))"), "6");+ assert_eq!(eval("of:=SORTBY([.A1:.A3];[.B1:.B3];-1)"), "3");+ assert_eq!(eval("of:=SUM(UNIQUE([.A1:.A3]))"), "6");+ // SEQUENCE composes with aggregations; bare displays first element.+ assert_eq!(eval("of:=SUM(SEQUENCE(4))"), "10");+ assert_eq!(eval("of:=SEQUENCE(4)"), "1");+ assert_eq!(eval("of:=SEQUENCE(2;2)"), "1");+ assert_eq!(eval("of:=SUM(SEQUENCE(2;2;10;10))"), "100");+ // LET binds names then evaluates.+ assert_eq!(eval("of:=LET(x;2;x*10)"), "20");+ assert_eq!(eval("of:=LET(x;2;y;3;x+y)"), "5");+ assert_eq!(eval("of:=LET(x;[.A1]+[.A2];x*2)"), "6");+ assert_eq!(eval("of:=LET(s;\"hi\";s&\"!\")"), "hi!");+ // ROWS sees through spilled arrays.+ assert_eq!(eval("of:=ROWS(FILTER([.A1:.A3];[.B1:.B3]>0))"), "3");+ // OFFSET with height/width spills; SUM composes.+ assert_eq!(eval("of:=SUM(OFFSET([.A1];0;0;3;1))"), "6");+ assert_eq!(eval("of:=OFFSET([.A1];1;1)"), "20");+ // LAMBDA is recognized but unsupported here.+ assert_eq!(eval("of:=LAMBDA(x;x+1)"), "#VALUE!");+ }+ #[test] fn format_value_json_standalone() { // No format ("null"/empty) -> plain number formatting.
office/src/main/rust/src/formula_part11.rs
diff --git a/office/src/main/rust/src/formula_part11.rs b/office/src/main/rust/src/formula_part11.rsnew file mode 100644index 0000000000..72314404c7--- /dev/null+++ b/office/src/main/rust/src/formula_part11.rs@@ -0,0 +1,129 @@+// ---- named-range address parsing ------------------------------------------+// Parses ODF named-range addresses (`Sheet.A1:Sheet.B2`) into engine Refs.+// Included into the formula module (see formula.rs); shares Ref/Sheet/col_to_index.++/// Renders one scalar to its display string (arrays reduce to their first+/// element). Split from Workbook::display_value for file length.+fn display_scalar(v: &Value, fmt: Option<&NumberFormat>) -> String {+ match v {+ Value::Num(x) => {+ if x.is_nan() {+ "#ERR".to_string()+ } else {+ format_with_style(*x, fmt)+ }+ }+ Value::Bool(b) => {+ if *b {+ "TRUE".to_string()+ } else {+ "FALSE".to_string()+ }+ }+ Value::Str(s) => s.clone(),+ Value::Err(code) => code.clone(),+ Value::Blank => String::new(),+ Value::Arr(vs) => display_scalar(&Value::first_of(vs), fmt),+ }+}++/// Parses an ODF named-range address (`Sheet.A1:Sheet.B2`, `Sheet.A1`, or a+/// space-separated union — first part wins) into a [Ref]. Sheet names are+/// matched against the workbook's sheets; an unknown sheet falls back to the+/// first sheet, mirroring the engine's lenient cross-sheet behavior.+fn parse_odf_address(+ addr: &str,+ sheets: &[Sheet],+ name_to_idx: &HashMap<String, usize>,+) -> Option<Ref> {+ if sheets.is_empty() {+ return None;+ }+ let mut first = addr.split_whitespace().next()?.trim();+ // Strip a leading "=" some exporters include.+ first = first.strip_prefix('=').unwrap_or(first);+ if first.is_empty() {+ return None;+ }+ // Split endpoints; a single endpoint is a one-cell range.+ let (a, b) = match first.split_once(':') {+ Some((x, y)) => (x.trim(), y.trim()),+ None => (first, first),+ };+ let (sheet_name, cell_a) = split_sheet_cell(a);+ let (_, cell_b) = split_sheet_cell(b);+ let (r1, c1) = parse_a1_coords(cell_a)?;+ let (r2, c2) = parse_a1_coords(cell_b)?;+ let sheet = sheet_name.filter(|s| !s.is_empty()).map(|s| {+ // Keep the canonical sheet name casing for eval_on lookups.+ sheets+ .iter()+ .find(|sh| sh.name.eq_ignore_ascii_case(&s))+ .map(|sh| sh.name.clone())+ .unwrap_or(s)+ });+ if let Some(ref s) = sheet {+ if !name_to_idx.keys().any(|k| k.eq_ignore_ascii_case(s)) {+ return None;+ }+ }+ Some(Ref {+ r1,+ c1,+ r2,+ c2,+ is_range: true,+ sheet,+ })+}++/// Splits `Sheet.A1` / `'My Sheet'.$A$1` / `A1` into (sheet, cell). The sheet+/// part is everything before the LAST dot (names may contain dots); the cell+/// part follows it.+fn split_sheet_cell(endpoint: &str) -> (Option<String>, &str) {+ let e = endpoint.trim().trim_start_matches('$');+ match e.rfind('.') {+ Some(i) => {+ let sheet = e[..i].trim().trim_matches('\'').trim_start_matches('$');+ let cell = e[i + 1..].trim();+ if sheet.is_empty() {+ (None, cell)+ } else {+ (Some(sheet.to_string()), cell)+ }+ }+ None => (None, e),+ }+}++/// Parses an A1 cell token (`$B$12`, `c3`) into 0-based (row, col).+fn parse_a1_coords(token: &str) -> Option<(i32, i32)> {+ let t = token.trim().replace('$', "");+ let chars: Vec<char> = t.chars().collect();+ let mut i = 0;+ while i < chars.len() && !chars[i].is_ascii_alphabetic() {+ i += 1;+ }+ let ls = i;+ while i < chars.len() && chars[i].is_ascii_alphabetic() {+ i += 1;+ }+ let letters: String = chars[ls..i].iter().collect();+ let ds = i;+ while i < chars.len() && chars[i].is_ascii_digit() {+ i += 1;+ }+ // Reject trailing junk (e.g. "#REF!" fragments) and missing parts.+ if i != chars.len() || letters.is_empty() || ds == i {+ return None;+ }+ let digits: String = chars[ds..i].iter().collect();+ if letters.len() > 3 {+ return None;+ }+ let row = digits.parse::<i32>().ok()? - 1;+ if row < 0 || row >= 1048576 {+ return None;+ }+ Some((row, col_to_index(&letters)))+}
office/src/main/rust/src/formula_part12.rs
diff --git a/office/src/main/rust/src/formula_part12.rs b/office/src/main/rust/src/formula_part12.rsnew file mode 100644index 0000000000..6ca32d742b--- /dev/null+++ b/office/src/main/rust/src/formula_part12.rs@@ -0,0 +1,279 @@+// ---- dynamic-array functions -------------------------------------------------+// XLOOKUP/FILTER/SORT/SORTBY/UNIQUE/SEQUENCE/LET implementations. Included into+// the formula module (see formula.rs); dispatched from apply_function4 in part8.++impl<'a> Evaluator<'a> {+ fn filter_fn(&mut self, a: &[ArgThunk]) -> R<Value> {+ let vals = self.t_values(&a[0])?;+ let include = self.include_values(&a[1])?;+ if vals.len() != include.len() {+ return Err(ferr("#CALC!"));+ }+ let mut out = Vec::new();+ for (v, inc) in vals.into_iter().zip(include) {+ if self.truthy(inc)? {+ out.push(v);+ }+ }+ if out.is_empty() {+ if a.len() > 2 && !a[2].text.trim().is_empty() {+ Ok(self.t_value(&a[2])?)+ } else {+ Err(ferr("#CALC!"))+ }+ } else {+ Ok(Value::Arr(out))+ }+ }++ fn sort_fn(&mut self, a: &[ArgThunk]) -> R<Value> {+ let mut vals = self.t_values(&a[0])?;+ let sort_index = if a.len() > 1 { self.t_num(&a[1])? as i32 } else { 1 };+ let order = if a.len() > 2 { self.t_num(&a[2])? as i32 } else { 1 };+ let _by_col = a.len() > 3 && self.t_truthy(&a[3])?;+ // Flattened vectors carry no 2-D shape: only a single vector sorts.+ if sort_index != 1 && sort_index != -1 {+ return Err(ferr("#VALUE!"));+ }+ if _by_col {+ return Err(ferr("#VALUE!"));+ }+ let desc = order == -1;+ vals.sort_by(|x, y| cmp_values(x, y));+ if desc {+ vals.reverse();+ }+ Ok(Value::Arr(vals))+ }++ fn sortby_fn(&mut self, a: &[ArgThunk]) -> R<Value> {+ let vals = self.t_values(&a[0])?;+ if a.len() < 2 {+ return Err(ferr("#VALUE!"));+ }+ let keys = self.t_values(&a[1])?;+ let order = if a.len() > 2 { self.t_num(&a[2])? as i32 } else { 1 };+ if vals.len() != keys.len() {+ return Err(ferr("#VALUE!"));+ }+ let mut paired: Vec<(Value, Value)> =+ keys.into_iter().zip(vals.into_iter()).collect();+ paired.sort_by(|x, y| cmp_values(&x.0, &y.0));+ if order == -1 {+ paired.reverse();+ }+ Ok(Value::Arr(paired.into_iter().map(|(_, v)| v).collect()))+ }++ fn unique_fn(&mut self, a: &[ArgThunk]) -> R<Value> {+ let vals = self.t_values(&a[0])?;+ let by_col = a.len() > 1 && self.t_truthy(&a[1])?;+ if by_col {+ return Err(ferr("#VALUE!"));+ }+ let exactly_once = a.len() > 2 && self.t_truthy(&a[2])?;+ let mut out = Vec::new();+ for v in &vals {+ if !out.contains(v) {+ let count = vals.iter().filter(|x| *x == v).count();+ if !exactly_once || count == 1 {+ out.push(v.clone());+ }+ }+ }+ if out.is_empty() {+ Err(ferr("#CALC!"))+ } else {+ Ok(Value::Arr(out))+ }+ }++ fn sequence_fn(&mut self, a: &[ArgThunk]) -> R<Value> {+ let rows = self.t_num(&a[0])? as i32;+ let cols = if a.len() > 1 { self.t_num(&a[1])? as i32 } else { 1 };+ let start = if a.len() > 2 { self.t_num(&a[2])? } else { 1.0 };+ let step = if a.len() > 3 { self.t_num(&a[3])? } else { 1.0 };+ if rows < 1 || cols < 1 {+ return Err(ferr("#VALUE!"));+ }+ if rows as i64 * cols as i64 > 1_000_000 {+ return Err(ferr("#CALC!"));+ }+ let mut out = Vec::with_capacity((rows * cols) as usize);+ for r in 0..rows {+ for c in 0..cols {+ out.push(Value::Num(start + (r * cols + c) as f64 * step));+ }+ }+ Ok(Value::Arr(out))+ }++ /// XLOOKUP(lookup, lookup_array, return_array, [if_not_found], [match_mode],+ /// [search_mode]). match_mode: 0 exact (default), -1 exact-or-next-smaller,+ /// 1 exact-or-next-larger, 2 wildcard. search_mode: 1 first-to-last+ /// (default), -1 last-to-first, 2 binary ascending, -2 binary descending.+ fn xlookup(&mut self, a: &[ArgThunk]) -> R<Value> {+ if a.len() < 3 {+ return Err(ferr("#VALUE!"));+ }+ let key = self.t_value(&a[0])?;+ let lv = self.t_values(&a[1])?;+ let rv = self.t_values(&a[2])?;+ if lv.is_empty() || rv.is_empty() {+ return Err(ferr("#N/A"));+ }+ let match_mode = if a.len() > 4 { self.t_num(&a[4])? as i32 } else { 0 };+ let search_mode = if a.len() > 5 { self.t_num(&a[5])? as i32 } else { 1 };+ let missing = |me: &mut Self| -> R<Value> {+ // An empty 4th arg counts as omitted (Excel `XLOOKUP(..;;..)`).+ if a.len() > 3 && !a[3].text.trim().is_empty() {+ me.t_value(&a[3])+ } else {+ Err(ferr("#N/A"))+ }+ };+ let at = |idx: usize| -> R<Value> {+ rv.get(idx).cloned().ok_or_else(|| ferr("#VALUE!"))+ };+ let order: Vec<usize> = match search_mode {+ -1 => (0..lv.len()).rev().collect(),+ _ => (0..lv.len()).collect(),+ };+ match match_mode {+ 2 => {+ // Wildcard: text pattern match, else exact equality.+ for i in order {+ if wildcard_match(&key, &lv[i])? {+ return at(i);+ }+ }+ missing(self)+ }+ -1 | 1 => {+ // Exact first, else next smaller (-1) / larger (1).+ for i in order.clone() {+ if self.compare_op("=", &lv[i], &key)? {+ return at(i);+ }+ }+ let mut best: Option<usize> = None;+ for i in order {+ let is_candidate = if match_mode == -1 {+ self.compare_op("<", &lv[i], &key)?+ || self.compare_op("=", &lv[i], &key)?+ } else {+ self.compare_op(">", &lv[i], &key)?+ || self.compare_op("=", &lv[i], &key)?+ };+ if !is_candidate {+ continue;+ }+ best = Some(match best {+ None => i,+ Some(b) => {+ let better = if match_mode == -1 {+ self.compare_op(">", &lv[i], &lv[b])?+ } else {+ self.compare_op("<", &lv[i], &lv[b])?+ };+ if better { i } else { b }+ }+ });+ }+ match best {+ Some(b) => at(b),+ None => missing(self),+ }+ }+ _ => {+ if search_mode == 2 || search_mode == -2 {+ // Binary search over a sorted array.+ let asc = search_mode == 2;+ let mut lo = 0i32;+ let mut hi = lv.len() as i32 - 1;+ while lo <= hi {+ let mid = (lo + hi) / 2;+ let ord = cmp_values(&lv[mid as usize], &key);+ let eq = ord == std::cmp::Ordering::Equal;+ if eq {+ return at(mid as usize);+ }+ let go_right = if asc {+ ord == std::cmp::Ordering::Less+ } else {+ ord == std::cmp::Ordering::Greater+ };+ if go_right {+ lo = mid + 1;+ } else {+ hi = mid - 1;+ }+ }+ missing(self)+ } else {+ for i in order {+ if self.compare_op("=", &lv[i], &key)? {+ return at(i);+ }+ }+ missing(self)+ }+ }+ }+ }++ /// FILTER's include argument: normally a range of booleans, but users write+ /// `FILTER(A:A;B:B>15)` — a comparison over a range. The scalar parser would+ /// collapse `[.B1:.B3]` to its top-left cell, so detect a top-level comparison+ /// with a range operand here and evaluate it elementwise (scalar sides+ /// broadcast). Anything else falls back to the ordinary value list.+ fn include_values(&mut self, t: &ArgThunk) -> R<Vec<Value>> {+ if let Some((op, left, right)) = split_top_compare(&t.text) {+ let l_ref = is_bare_ref_text(&left);+ let r_ref = is_bare_ref_text(&right);+ if l_ref || r_ref {+ let lt = ArgThunk { text: left };+ let rt = ArgThunk { text: right };+ let mut lv = self.t_values(<)?;+ let mut rv = self.t_values(&rt)?;+ if lv.len() == 1 && rv.len() > 1 {+ lv = vec![lv[0].clone(); rv.len()];+ } else if rv.len() == 1 && lv.len() > 1 {+ rv = vec![rv[0].clone(); lv.len()];+ }+ if lv.len() != rv.len() {+ return Err(ferr("#CALC!"));+ }+ let mut out = Vec::with_capacity(lv.len());+ for (l, r) in lv.into_iter().zip(rv) {+ out.push(Value::Bool(self.compare_op(&op, &l, &r)?));+ }+ return Ok(out);+ }+ }+ self.t_values(t)+ }++ /// LET(name1, value1, …, calc): binds scalar names, then evaluates calc with+ /// token-boundary substitution (string literals and [refs] untouched).+ fn let_bind(&mut self, a: &[ArgThunk]) -> R<Value> {+ if a.len() < 3 || a.len() % 2 == 0 {+ return Err(ferr("#VALUE!"));+ }+ let mut bindings: Vec<(String, String)> = Vec::new();+ let mut i = 0;+ while i + 1 < a.len() - 1 {+ let raw_name = a[i].text.trim().to_uppercase();+ if !is_let_name(&raw_name) {+ return Err(ferr("#NAME?"));+ }+ // Eager, like Excel: a binding error propagates even if unused.+ let v = self.t_value(&a[i + 1])?;+ bindings.push((raw_name, value_literal(&v)?));+ i += 2;+ }+ let calc = substitute_let_names(&a[a.len() - 1].text, &bindings);+ let mut p = Parser::new(&calc);+ p.parse_expression(self)+ }+}
office/src/main/rust/src/formula_part13.rs
diff --git a/office/src/main/rust/src/formula_part13.rs b/office/src/main/rust/src/formula_part13.rsnew file mode 100644index 0000000000..c458aaa53e--- /dev/null+++ b/office/src/main/rust/src/formula_part13.rs@@ -0,0 +1,274 @@+// ---- dynamic-array helpers -------------------------------------------------+// Elementwise FILTER evaluation, Excel ordering, LET substitution.+// Included into the formula module (see formula.rs).++/// Splits thunk text at the first top-level comparison operator (`<=`, `>=`,+/// `<>`, `<`, `>`, `=`), skipping string literals, [bracketed refs] and+/// (parenthesized groups). Returns (op, left, right).+fn split_top_compare(text: &str) -> Option<(String, String, String)> {+ let chars: Vec<char> = text.chars().collect();+ let mut i = 0;+ while i < chars.len() {+ let c = chars[i];+ if c == '"' {+ i += 1;+ while i < chars.len() {+ if chars[i] == '"' {+ if i + 1 < chars.len() && chars[i + 1] == '"' {+ i += 2;+ continue;+ }+ i += 1;+ break;+ }+ i += 1;+ }+ continue;+ }+ if c == '[' {+ i += 1;+ while i < chars.len() && chars[i] != ']' {+ i += 1;+ }+ i += 1;+ continue;+ }+ if c == '(' {+ let mut depth = 1;+ i += 1;+ while i < chars.len() && depth > 0 {+ if chars[i] == '"' {+ i += 1;+ while i < chars.len() && chars[i] != '"' {+ i += 1;+ }+ i += 1;+ continue;+ }+ if chars[i] == '(' {+ depth += 1;+ } else if chars[i] == ')' {+ depth -= 1;+ }+ i += 1;+ }+ continue;+ }+ if c == '<' || c == '>' || c == '=' {+ let op = if i + 1 < chars.len() && chars[i + 1] == '>' && c == '<' {+ "<>".to_string()+ } else if i + 1 < chars.len() && chars[i + 1] == '=' {+ format!("{}=", c)+ } else if c == '=' {+ "=".to_string()+ } else {+ c.to_string()+ };+ let left: String = chars[..i].iter().collect();+ let right: String = chars[i + op.len()..].iter().collect();+ if left.trim().is_empty() || right.trim().is_empty() {+ return None;+ }+ return Some((op, left, right));+ }+ i += 1;+ }+ None+}++/// True when the text is a bare range operand: a [bracketed ref] or a named+/// range (letters/underscore/dots, not a call).+fn is_bare_ref_text(text: &str) -> bool {+ let t = text.trim();+ if t.starts_with('[') {+ return true;+ }+ if t.contains('(') || t.contains('"') {+ return false;+ }+ let mut chars = t.chars();+ match chars.next() {+ Some(c) if c.is_ascii_alphabetic() || c == '_' => {}+ _ => return false,+ }+ t.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')+}++/// Excel sort rank for total ordering: numbers < text < logicals < blanks;+/// errors sort last.+fn rank_of(v: &Value) -> u8 {+ match v {+ Value::Num(_) => 0,+ Value::Str(_) => 1,+ Value::Bool(_) => 2,+ Value::Blank => 3,+ Value::Err(_) => 4,+ Value::Arr(_) => 5,+ }+}++/// Total ordering mirroring Excel's sort: by type rank, then by value+/// (numbers numerically, text case-insensitively, FALSE < TRUE).+fn cmp_values(a: &Value, b: &Value) -> std::cmp::Ordering {+ let ra = rank_of(a);+ let rb = rank_of(b);+ if ra != rb {+ return ra.cmp(&rb);+ }+ match (a, b) {+ (Value::Num(x), Value::Num(y)) => x.total_cmp(y),+ (Value::Str(x), Value::Str(y)) => {+ x.to_uppercase().cmp(&y.to_uppercase()).then_with(|| x.cmp(y))+ }+ (Value::Bool(x), Value::Bool(y)) => x.cmp(y),+ (Value::Err(x), Value::Err(y)) => x.cmp(y),+ (Value::Arr(x), Value::Arr(y)) => {+ x.len().cmp(&y.len()).then_with(|| {+ x.iter().zip(y.iter()).map(|(p, q)| cmp_values(p, q)).find(|o| *o != std::cmp::Ordering::Equal).unwrap_or(std::cmp::Ordering::Equal)+ })+ }+ _ => std::cmp::Ordering::Equal,+ }+}++/// XLOOKUP match_mode=2: wildcard text match, else exact equality.+fn wildcard_match(key: &Value, candidate: &Value) -> R<bool> {+ match (key, candidate) {+ (Value::Str(pat), Value::Str(s)) => Ok(wildcard_equals(s, pat)),+ _ => {+ // Numbers/bools fall back to exact equality.+ let eq = match (key, candidate) {+ (Value::Num(x), Value::Num(y)) => x == y,+ (Value::Bool(x), Value::Bool(y)) => x == y,+ (Value::Blank, Value::Blank) => true,+ _ => {+ let ks = format_scalar(key);+ let cs = format_scalar(candidate);+ ks.eq_ignore_ascii_case(&cs)+ }+ };+ Ok(eq)+ }+ }+}++fn format_scalar(v: &Value) -> String {+ match v {+ Value::Num(x) => format_number(*x),+ Value::Bool(b) => {+ if *b {+ "TRUE".to_string()+ } else {+ "FALSE".to_string()+ }+ }+ Value::Str(s) => s.clone(),+ Value::Err(c) => c.clone(),+ Value::Blank => String::new(),+ Value::Arr(vs) => format_scalar(&Value::first_of(vs)),+ }+}++/// True for a valid LET binding name: starts with a letter/underscore, continues+/// with letters/digits/underscore/dot, and is not itself a cell reference.+fn is_let_name(name: &str) -> bool {+ if name.is_empty() {+ return false;+ }+ let mut chars = name.chars();+ let first = chars.next().unwrap();+ if !first.is_ascii_alphabetic() && first != '_' {+ return false;+ }+ if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') {+ return false;+ }+ // Reject A1-style cell refs (letters then digits, e.g. X1, AB12).+ let letters = name.chars().take_while(|c| c.is_ascii_alphabetic()).count();+ if letters > 0 && letters <= 3 && name[letters..].chars().all(|c| c.is_ascii_digit()) && !name[letters..].is_empty() {+ return false;+ }+ // Reject function/constant names already meaningful to the parser.+ !matches!(name, "TRUE" | "FALSE" | "PI")+}++/// Renders a scalar binding value as a re-parseable literal. Arrays reduce to+/// their first element (documented scalar simplification); errors propagate.+fn value_literal(v: &Value) -> R<String> {+ match v {+ Value::Num(x) => Ok(format_number(*x)),+ Value::Str(s) => Ok(format!("\"{}\"", s.replace('"', "\"\""))),+ Value::Bool(b) => Ok(if *b { "TRUE".to_string() } else { "FALSE".to_string() }),+ Value::Blank => Ok("0".to_string()),+ Value::Err(c) => Err(EvalError(c.clone())),+ Value::Arr(vs) => value_literal(&Value::first_of(vs)),+ }+}++/// Substitutes LET bindings into calc text at token boundaries, skipping+/// string literals and [bracketed refs]. Matching is case-insensitive+/// (bindings are stored uppercase).+fn substitute_let_names(calc: &str, bindings: &[(String, String)]) -> String {+ if bindings.is_empty() {+ return calc.to_string();+ }+ let chars: Vec<char> = calc.chars().collect();+ let mut out = String::new();+ let mut i = 0;+ while i < chars.len() {+ let c = chars[i];+ if c == '"' {+ // Copy string literal verbatim ("" = escaped quote).+ out.push(c);+ i += 1;+ while i < chars.len() {+ out.push(chars[i]);+ if chars[i] == '"' {+ if i + 1 < chars.len() && chars[i + 1] == '"' {+ out.push(chars[i + 1]);+ i += 2;+ continue;+ }+ i += 1;+ break;+ }+ i += 1;+ }+ continue;+ }+ if c == '[' {+ // Copy bracketed ref verbatim.+ out.push(c);+ i += 1;+ while i < chars.len() && chars[i] != ']' {+ out.push(chars[i]);+ i += 1;+ }+ if i < chars.len() {+ out.push(chars[i]);+ i += 1;+ }+ continue;+ }+ if c.is_ascii_alphabetic() || c == '_' {+ let start = i;+ while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_' || chars[i] == '.') {+ i += 1;+ }+ let tok: String = chars[start..i].iter().collect();+ let upper = tok.to_uppercase();+ match bindings.iter().find(|(n, _)| *n == upper) {+ Some((_, lit)) => {+ out.push('(');+ out.push_str(lit);+ out.push(')');+ }+ None => out.push_str(&tok),+ }+ continue;+ }+ out.push(c);+ i += 1;+ }+ out+}
office/src/main/rust/src/formula_part2.rs
diff --git a/office/src/main/rust/src/formula_part2.rs b/office/src/main/rust/src/formula_part2.rsindex 78f2c6578a..573e158b29 100644--- a/office/src/main/rust/src/formula_part2.rs+++ b/office/src/main/rust/src/formula_part2.rs@@ -69,6 +69,8 @@ impl<'a> Evaluator<'a> { Value::Str(s) => parse_f64(&s).ok_or_else(|| ferr("#VALUE!")), Value::Blank => Ok(0.0), Value::Err(c) => Err(EvalError(c)),+ // Implicit intersection for spilled arrays.+ Value::Arr(vs) => self.num(Value::first_of(&vs)), } } @@ -76,6 +78,7 @@ impl<'a> Evaluator<'a> { match v { Value::Num(x) => Some(*x), Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),+ Value::Arr(vs) => self.num_or_null(&Value::first_of(vs)), _ => None, } }@@ -87,6 +90,7 @@ impl<'a> Evaluator<'a> { Value::Str(s) => Ok(s), Value::Blank => Ok(String::new()), Value::Err(c) => Err(EvalError(c)),+ Value::Arr(vs) => self.str_of(Value::first_of(&vs)), } } @@ -108,6 +112,7 @@ impl<'a> Evaluator<'a> { } Value::Blank => Ok(false), Value::Err(c) => Err(EvalError(c)),+ Value::Arr(vs) => self.truthy(Value::first_of(&vs)), } } @@ -134,7 +139,8 @@ impl<'a> Evaluator<'a> { continue; } }- out.push(self.eval_on(sheet_ref, r, c)?);+ // A cell whose own formula spills an array contributes its elements.+ out.extend(expand_value(self.eval_on(sheet_ref, r, c)?)); } } Ok(out)@@ -142,7 +148,7 @@ impl<'a> Evaluator<'a> { fn arg_values(&mut self, arg: &Arg) -> R<Vec<Value>> { match arg {- Arg::Scalar(v) => Ok(vec![v.clone()]),+ Arg::Scalar(v) => Ok(expand_value(v.clone())), Arg::RangeRef { r1, c1,@@ -173,6 +179,7 @@ impl<'a> Evaluator<'a> { let a = self.t_arg(t)?; match a { Arg::Scalar(v) => Ok(v),+ // Scalar context: top-left for ranges, first element for arrays. Arg::RangeRef { r1, c1, sheet, .. } => self.eval_on(&sheet, r1, c1), } }@@ -183,10 +190,22 @@ impl<'a> Evaluator<'a> { } fn t_ref(&mut self, t: &ArgThunk) -> Option<Ref> {+ let txt = t.text.trim();+ // A bare name that isn't bracketed may be a named range ("MyRange").+ if !txt.starts_with('[') && !txt.contains('(') {+ if let Some(r) = self.named_ref(txt) {+ return Some(r);+ }+ } let mut p = Parser::new(&t.text); p.parse_ref_top() } + /// Resolves a named range to its [Ref], or None when unknown.+ fn named_ref(&self, name: &str) -> Option<Ref> {+ self.wb.named.get(&name.trim().to_uppercase()).cloned()+ }+ fn t_num(&mut self, t: &ArgThunk) -> R<f64> { let v = self.t_value(t)?; self.num(v)@@ -224,6 +243,7 @@ impl<'a> Evaluator<'a> { Value::Blank => Ok(Some(0.0)), Value::Err(c) => Err(EvalError(c.clone())), Value::Str(_) => Ok(None),+ Value::Arr(vs) => self.cmp_num(&Value::first_of(vs)), } } @@ -293,6 +313,15 @@ impl<'a> Evaluator<'a> { } } +/// Expands a value into the flat list an aggregation consumes: arrays spill+/// their elements, scalars contribute themselves.+fn expand_value(v: Value) -> Vec<Value> {+ match v {+ Value::Arr(vs) => vs.into_iter().flat_map(expand_value).collect(),+ other => vec![other],+ }+}+ fn raw_cell_value(cell: &Cell) -> Value { if let Some(n) = cell.number_value { return Value::Num(n);
office/src/main/rust/src/formula_part3.rs
diff --git a/office/src/main/rust/src/formula_part3.rs b/office/src/main/rust/src/formula_part3.rsindex f9f1573808..474e5dac2f 100644--- a/office/src/main/rust/src/formula_part3.rs+++ b/office/src/main/rust/src/formula_part3.rs@@ -41,6 +41,42 @@ impl Parser { fn parse_arg_top(&mut self, ev: &mut Evaluator) -> R<Arg> { self.skip_ws();+ // A bare name may be a named range ("MyRange") — resolve before the+ // bracket fast-path below.+ if self.peek() != '[' && self.peek() != '"' {+ let save = self.pos;+ let start = self.pos;+ while self.pos < self.s.len() {+ let c = self.s[self.pos];+ if c.is_alphanumeric() || c == '_' || c == '.' {+ self.pos += 1;+ } else {+ break;+ }+ }+ if self.pos > start {+ let name = self.substr(start, self.pos).to_uppercase();+ self.skip_ws();+ // Only a bare token (end of arg) can be a name; `FOO(` is a call.+ if self.pos >= self.s.len() && ev.wb.named.contains_key(&name) {+ let r = ev.wb.named[&name].clone();+ return if r.is_range {+ Ok(Arg::RangeRef {+ r1: r.r1,+ c1: r.c1,+ r2: r.r2,+ c2: r.c2,+ sheet: r.sheet,+ })+ } else {+ Ok(Arg::Scalar(ev.eval_on(&r.sheet, r.r1, r.c1)?))+ };+ }+ // Not a name (or not bare): rewind so the expression parser+ // re-reads the token as a function/constant.+ self.pos = save;+ }+ } if self.peek() == '[' { let save = self.pos; let r = self.parse_ref_raw();@@ -334,7 +370,12 @@ impl Parser { "TRUE" => Ok(Value::Bool(true)), "FALSE" => Ok(Value::Bool(false)), "PI" => Ok(Value::Num(std::f64::consts::PI)),- _ => Err(ferr("#NAME?")),+ // A bare name that isn't a constant may be a named range+ // ("=MyCell+1", "=SUM(MyRange)").+ _ => match ev.wb.named.get(&name) {+ Some(r) => ev.eval_on(&r.sheet.clone(), r.r1, r.c1),+ None => Err(ferr("#NAME?")),+ }, }; } self.pos += 1; // '('
office/src/main/rust/src/formula_part5.rs
diff --git a/office/src/main/rust/src/formula_part5.rs b/office/src/main/rust/src/formula_part5.rsindex 462d7bf7e3..280a6ddffb 100644--- a/office/src/main/rust/src/formula_part5.rs+++ b/office/src/main/rust/src/formula_part5.rs@@ -14,6 +14,19 @@ impl<'a> Evaluator<'a> { Value::Str(_) => out.push(0.0), Value::Blank => {} Value::Err(c) => return Err(EvalError(c)),+ // all_vals already expands arrays; a nested Arr can only arrive+ // via a cell holding a spilled result — count its first element.+ Value::Arr(vs) => {+ let first = Value::first_of(&vs);+ match first {+ Value::Num(x) => out.push(x),+ Value::Bool(b) => out.push(if b { 1.0 } else { 0.0 }),+ Value::Str(_) => out.push(0.0),+ Value::Blank => {}+ Value::Err(c) => return Err(EvalError(c)),+ Value::Arr(_) => {}+ }+ } } } Ok(out)
office/src/main/rust/src/formula_part6.rs
diff --git a/office/src/main/rust/src/formula_part6.rs b/office/src/main/rust/src/formula_part6.rsindex 1f2b00c268..cce25a4c2c 100644--- a/office/src/main/rust/src/formula_part6.rs+++ b/office/src/main/rust/src/formula_part6.rs@@ -350,10 +350,13 @@ impl<'a> Evaluator<'a> { // ---- lookup dimensions ---- "ROWS" => match self.t_arg(&a[0])? { Arg::RangeRef { r1, r2, .. } => Ok(Value::Num(((r2 - r1).abs() + 1) as f64)),+ Arg::Scalar(Value::Arr(vs)) => Ok(Value::Num(vs.len() as f64)), _ => Ok(Value::Num(1.0)), }, "COLUMNS" => match self.t_arg(&a[0])? { Arg::RangeRef { c1, c2, .. } => Ok(Value::Num(((c2 - c1).abs() + 1) as f64)),+ // Flattened arrays carry no shape; a spilled vector is one column.+ Arg::Scalar(Value::Arr(_)) => Ok(Value::Num(1.0)), _ => Ok(Value::Num(1.0)), },
office/src/main/rust/src/formula_part7.rs
diff --git a/office/src/main/rust/src/formula_part7.rs b/office/src/main/rust/src/formula_part7.rsindex 2b68093f43..a41b3b5695 100644--- a/office/src/main/rust/src/formula_part7.rs+++ b/office/src/main/rust/src/formula_part7.rs@@ -164,6 +164,7 @@ impl<'a> Evaluator<'a> { Value::Num(x) => Ok(Value::Num(x)), Value::Bool(b) => Ok(Value::Num(if b { 1.0 } else { 0.0 })), Value::Err(c) => Ok(Value::Err(c)),+ Value::Arr(vs) => Ok(Value::Num(self.num(Value::first_of(&vs))?)), _ => Ok(Value::Num(0.0)), }, "TYPE" => Ok(Value::Num(match self.safe_value(&a[0]) {@@ -172,6 +173,8 @@ impl<'a> Evaluator<'a> { Value::Bool(_) => 4.0, Value::Err(_) => 16.0, Value::Blank => 1.0,+ // Excel TYPE of an array constant.+ Value::Arr(_) => 64.0, })), "ERROR.TYPE" => { let code = self.is_error(&a[0]);@@ -183,6 +186,7 @@ impl<'a> Evaluator<'a> { Some("#NAME?") => Some(5), Some("#NUM!") => Some(6), Some("#N/A") => Some(7),+ Some("#CALC!") => Some(14), _ => None, }; match t {
office/src/main/rust/src/formula_part8.rs
diff --git a/office/src/main/rust/src/formula_part8.rs b/office/src/main/rust/src/formula_part8.rsindex 1e6dce110a..30cfffb5ce 100644--- a/office/src/main/rust/src/formula_part8.rs+++ b/office/src/main/rust/src/formula_part8.rs@@ -331,7 +331,28 @@ impl<'a> Evaluator<'a> { let r = self.t_ref(&a[0]).ok_or_else(|| ferr("#REF!"))?; let dr = self.t_num(&a[1])? as i32; let dc = self.t_num(&a[2])? as i32;- self.eval_on(&r.sheet, r.r1.min(r.r2) + dr, r.c1.min(r.c2) + dc)+ let base_r = r.r1.min(r.r2) + dr;+ let base_c = r.c1.min(r.c2) + dc;+ if base_r < 0 || base_c < 0 {+ return Err(ferr("#REF!"));+ }+ let h = if a.len() > 3 { self.t_num(&a[3])? as i32 } else { 1 };+ let w = if a.len() > 4 { self.t_num(&a[4])? as i32 } else { 1 };+ if h <= 0 || w <= 0 {+ return Err(ferr("#REF!"));+ }+ if h == 1 && w == 1 {+ self.eval_on(&r.sheet, base_r, base_c)+ } else {+ // A multi-cell result spills as an array (composes with SUM etc.).+ let mut out = Vec::new();+ for rr in base_r..base_r + h {+ for cc in base_c..base_c + w {+ out.push(self.eval_on(&r.sheet, rr, cc)?);+ }+ }+ Ok(Value::Arr(out))+ } } "ADDRESS" => { let row = self.t_num(&a[0])? as i32;@@ -363,6 +384,24 @@ impl<'a> Evaluator<'a> { self.t_str(&a[0])? })), + // ---- dynamic arrays (scalar-friendly subset) ----+ //+ // This engine has no spill grid: a cell shows one value. Array results+ // are kept as Value::Arr — aggregations (SUM/AVERAGE/…) expand them, and+ // a bare array in a cell displays its first element (implicit+ // intersection, like pre-dynamic-array Excel).+ "XLOOKUP" => self.xlookup(a),+ "FILTER" => self.filter_fn(a),+ "SORT" => self.sort_fn(a),+ "SORTBY" => self.sortby_fn(a),+ "UNIQUE" => self.unique_fn(a),+ "SEQUENCE" => self.sequence_fn(a),+ "LET" => self.let_bind(a),+ // LAMBDA needs first-class functions (MAP/REDUCE/… helpers), which this+ // engine has no plumbing for. Recognized so it reports #VALUE!+ // ("right name, can't compute here") instead of #NAME? ("unknown").+ "LAMBDA" => Err(ferr("#VALUE!")),+ _ => Err(ferr("#NAME?")), } }@@ -387,7 +426,7 @@ impl<'a> Evaluator<'a> { fn for_each_range_cell(&mut self, arg: &Arg) -> R<Vec<Value>> { let mut out = Vec::new(); match arg {- Arg::Scalar(v) => out.push(v.clone()),+ Arg::Scalar(v) => out.extend(expand_value(v.clone())), Arg::RangeRef { r1, c1, r2, c2, .. } => { for r in (*r1).min(*r2)..=(*r1).max(*r2) { for c in (*c1).min(*c2)..=(*c1).max(*c2) {@@ -396,7 +435,7 @@ impl<'a> Evaluator<'a> { continue; } }- out.push(self.evaluate_cell_v(r, c)?);+ out.extend(expand_value(self.evaluate_cell_v(r, c)?)); } } }@@ -444,4 +483,4 @@ impl<'a> Evaluator<'a> { } Ok(Value::Num(reduce(&matched))) }-}\ No newline at end of file+}
office/src/test/java/com/vayunmathur/office/odf/OdfListNumberingTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OdfListNumberingTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OdfListNumberingTest.ktindex a9e0865827..3cc7be7f57 100644--- a/office/src/test/java/com/vayunmathur/office/odf/OdfListNumberingTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/OdfListNumberingTest.kt@@ -79,8 +79,7 @@ class OdfListNumberingTest { @Test fun itemStartValueRestartsNumbering() { val d = doc(- """<text:list" +- "text:style-name="L1">${item("a")}${item("b", """ text:start-value="7"""")}${item("c")}</text:list>"""+ """<text:list text:style-name="L1">${item("a")}${item("b", """ text:start-value="7"""")}${item("c")}</text:list>""" ) assertEquals(listOf(1, 7, 8), numbers(d)) }
office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt b/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.ktindex f509d5e60e..50f02e9dad 100644--- a/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt+++ b/office/src/test/java/com/vayunmathur/office/odf/OoxmlImporterTest.kt@@ -52,6 +52,41 @@ class OoxmlImporterTest { assertEquals("of:=IF([.A1]>0;\"y\";\"n\")", ExcelFormula.toOdf("IF(A1>0,\"y\",\"n\")")) } + @Test fun excelFormulaWholeColumnRow() {+ assertEquals("of:=SUM([.A1:.A1048576])", ExcelFormula.toOdf("SUM(A:A)"))+ assertEquals("of:=SUM([.A1:.C1048576])", ExcelFormula.toOdf("SUM(A:C)"))+ assertEquals("of:=SUM([.A2:.XFD2])", ExcelFormula.toOdf("SUM(2:2)"))+ assertEquals("of:=SUM([.A2:.XFD5])", ExcelFormula.toOdf("SUM(2:5)"))+ assertEquals("of:=SUM([\$Data.A1:.C1048576])", ExcelFormula.toOdf("SUM(Data!A:C)"))+ // Absolute markers survive the expansion.+ assertEquals("of:=SUM([.\$A1:.\$A1048576])", ExcelFormula.toOdf("SUM(\$A:\$A)"))+ }++ @Test fun excelFormulaFromOdfRoundTrip() {+ assertEquals("=SUM(A1:A3)+B1", ExcelFormula.fromOdf("of:=SUM([.A1:.A3])+[.B1]"))+ assertEquals("=IF(A1>0,\"y\",\"n\")", ExcelFormula.fromOdf("of:=IF([.A1]>0;\"y\";\"n\")"))+ // Absolute markers round-trip.+ assertEquals("=\$A\$1+B2", ExcelFormula.fromOdf("of:=[\$A\$1]+[.B2]"))+ // Whole spans collapse back.+ assertEquals("=SUM(A:A)", ExcelFormula.fromOdf("of:=SUM([.A1:.A1048576])"))+ assertEquals("=SUM(2:5)", ExcelFormula.fromOdf("of:=SUM([.A2:.XFD5])"))+ // Sheet-qualified refs.+ assertEquals("=Data!A1", ExcelFormula.fromOdf("of:=[\$Data.A1]"))+ assertEquals("='My Sheet'!A1", ExcelFormula.fromOdf("of:=[$'My Sheet'.A1]"))+ }++ @Test fun excelFormulaShift() {+ assertEquals("A2", ExcelFormula.shift("A1", 1, 0))+ // Column absolute: letter kept, row still shifts.+ assertEquals("\$A6", ExcelFormula.shift("\$A1", 5, 5))+ // Row absolute: row kept.+ assertEquals("A\$1", ExcelFormula.shift("A\$1", 5, 0))+ assertEquals("B3", ExcelFormula.shift("A1", 2, 1))+ assertEquals("SUM(A2:A4)+\"A1\"", ExcelFormula.shift("SUM(A1:A3)+\"A1\"", 1, 0))+ // Sheet qualifiers are untouched; the cell part shifts.+ assertEquals("S2!B2", ExcelFormula.shift("S2!A1", 1, 1))+ }+ @Test fun excelNumberFormats() { val pct = ExcelNumFmt.parse("0.00%")!! assertTrue(pct.percent)@@ -157,6 +192,22 @@ class OoxmlImporterTest { assertEquals(3.14, sheet.rows[1].cells[0].numberValue!!, 0.0001) } + /**+ * Formatted cells must import even when the native formatter can't load (JVM unit+ * tests): the Kotlin fallback renders the display string and the numeric value survives.+ */+ @Test fun xlsxFormattedCellsSurviveWithoutNativeEngine() {+ val doc = OoxmlImporter.import(zipless(XLSX_FORMATTED_ENTRIES), "fmt.xlsx") as OdfDocument.Spreadsheet+ val sheet = doc.sheets[0]+ // 0.5 with builtin 0.00% -> "50.00%".+ assertEquals("50.00%", sheet.rows[0].cells[0].text)+ assertEquals(0.5, sheet.rows[0].cells[0].numberValue!!, 0.0001)+ // 1234.5 with builtin #,##0.00 -> "1,234.50".+ assertEquals("1,234.50", sheet.rows[0].cells[1].text)+ // 45292 with builtin mm-dd-yy -> date value type (ISO display in fallback).+ assertEquals("date", sheet.rows[0].cells[2].valueType)+ }+ // ---- PPTX ---- @Test fun pptxImportsShapeText() {@@ -195,11 +246,11 @@ class OoxmlImporterTest { "<c:chartSpace xmlns:c=\"c\"><c:chart><c:plotArea><c:barChart>" + "<c:barDir val=\"col\"/><c:grouping val=\"clustered\"/>" + "<c:ser><c:tx><c:v>S1</c:v></c:tx>" +- "<c:cat><c:strRef><c:strCache><c:pt idx=\"0\"><c:v>A</c:v></c:pt><c:pt" ++"<c:cat><c:strRef><c:strCache><c:pt idx=\"0\"><c:v>A</c:v></c:pt><c:pt " + "idx=\"1\"><c:v>B</c:v></c:pt></c:strCache></c:strRef></c:cat>" +- "<c:val><c:numRef><c:numCache><c:pt idx=\"0\"><c:v>10</c:v></c:pt><c:pt" ++"<c:val><c:numRef><c:numCache><c:pt idx=\"0\"><c:v>10</c:v></c:pt><c:pt " + "idx=\"1\"><c:v>20</c:v></c:pt></c:numCache></c:numRef></c:val>" +- "</c:ser></c:barChart></c:plotArea><c:legend><c:legendPos" ++ "</c:ser></c:barChart></c:plotArea><c:legend><c:legendPos " + "val=\"r\"/></c:legend></c:chart></c:chartSpace>" private const val OMML_FRAC =@@ -213,7 +264,7 @@ class OoxmlImporterTest { "<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Bold</w:t></w:r></w:p>" + "<w:tbl><w:tr><w:tc><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>" + "<w:tc><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc></w:tr></w:tbl>" +- "<w:p><w:pPr><w:numPr><w:ilvl w:val=\"0\"/><w:numId" ++"<w:p><w:pPr><w:numPr><w:ilvl w:val=\"0\"/><w:numId " + "w:val=\"1\"/></w:numPr></w:pPr><w:r><w:t>Item</w:t></w:r></w:p>" + "</w:body></w:document>"), "word/numbering.xml" to (@@ -231,10 +282,30 @@ class OoxmlImporterTest { "</sheetData><mergeCells count=\"1\"><mergeCell ref=\"A1:B1\"/></mergeCells></worksheet>") ) + private val XLSX_FORMATTED_ENTRIES = mapOf(+ "xl/workbook.xml" to ("<workbook xmlns=\"s\" xmlns:r=\"r\">" ++ "<sheets><sheet name=\"F\" sheetId=\"1\" r:id=\"rId1\"/></sheets></workbook>"),+ "xl/_rels/workbook.xml.rels" to ("<Relationships xmlns=\"p\">" ++ "<Relationship Id=\"rId1\" Type=\"t/worksheet\" Target=\"worksheets/sheet1.xml\"/>" ++ "</Relationships>"),+ "xl/styles.xml" to ("<styleSheet xmlns=\"s\">" ++ "<cellXfs count=\"4\">" ++ "<xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/>" ++ "<xf numFmtId=\"10\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/>" ++ "<xf numFmtId=\"4\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/>" ++ "<xf numFmtId=\"14\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/>" ++ "</cellXfs></styleSheet>"),+ "xl/worksheets/sheet1.xml" to ("<worksheet xmlns=\"s\"><sheetData><row r=\"1\">" ++ "<c r=\"A1\" s=\"1\"><v>0.5</v></c>" ++ "<c r=\"B1\" s=\"2\"><v>1234.5</v></c>" ++ "<c r=\"C1\" s=\"3\"><v>45292</v></c>" ++ "</row></sheetData></worksheet>")+ )+ private val PPTX_ENTRIES = mapOf( "ppt/slides/slide1.xml" to ( "<p:sld xmlns:p=\"p\" xmlns:a=\"a\"><p:cSld><p:spTree>" +- "<p:sp><p:spPr><a:xfrm><a:off x=\"914400\"" ++"<p:sp><p:spPr><a:xfrm><a:off x=\"914400\" " + "y=\"914400\"/><a:ext cx=\"1828800\" cy=\"457200\"/></a:xfrm>" + "<a:prstGeom prst=\"rect\"/></p:spPr>" + "<p:txBody><a:p><a:r><a:rPr b=\"1\" sz=\"2400\"/><a:t>Hi</a:t></a:r></a:p></p:txBody></p:sp>" +