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.

WIP xlsx: colour, ref, style and cell model core

Chethan6169a2a65c7b44d
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 9a1f99c..8a09834 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -76,6 +76,11 @@ android {
buildFeatures {
compose = true
}
+ testOptions {
+ // Plain JVM unit tests (the xlsx model/writer). Android stubs return defaults instead of
+ // throwing so incidental framework calls don't fail a pure-logic test.
+ unitTests.isReturnDefaultValues = true
+ }
// Bundling on-device OCR (bundled ML Kit + Tesseract4Android) added native .so libs for
// 4 CPU architectures; without splitting, every install carries all 4. This produces one
// APK per ABI (~1/4 the native-lib weight each) plus a universal fallback for sideloading.
@@ -160,4 +165,8 @@ dependencies {
implementation(libs.coil.compose)
implementation(libs.acccompanist.permissions)
implementation("androidx.documentfile:documentfile:1.0.1")
+
+ testImplementation("junit:junit:4.13.2")
+ // A real XmlPullParser for JVM tests; android.jar only carries stubs of it.
+ testImplementation("net.sf.kxml:kxml2:2.3.0")
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt b/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt
index a9ea26f..aa19b0b 100644
--- a/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/ExcelCellFormat.kt
@@ -53,9 +53,50 @@ internal object ExcelCellFormat {
* behaviour and never worse than it.
*/
fun formatCodesFor(numFmtIdByStyle: List<Int>, customCodes: Map<Int, String>): List<String> =
- numFmtIdByStyle.map { id ->
- customCodes[id] ?: if (id == 14) ShortDatePattern else (BuiltIn[id] ?: "General")
+ numFmtIdByStyle.map { id -> codeFor(id, customCodes) }
+
+ /** One `numFmtId` → its format code (custom first, then the built-in table). */
+ fun codeFor(id: Int, customCodes: Map<Int, String>): String =
+ customCodes[id] ?: if (id == 14) ShortDatePattern else (BuiltIn[id] ?: "General")
+
+ /** The built-in id whose code is exactly [code], or null when it has to be a custom `numFmt`. */
+ fun builtInIdFor(code: String): Int? =
+ if (code.equals("General", true)) 0 else BuiltIn.entries.firstOrNull { it.value == code && it.key != 14 }?.key
+
+ /** True when [code] renders serials as dates/times. */
+ fun isDateCode(code: String?): Boolean {
+ if (code.isNullOrBlank() || code.equals("General", true)) return false
+ val body = splitSections(code).firstOrNull()?.replace(Regex("\\[(?!h+]|hh+])[^]]*]", RegexOption.IGNORE_CASE), "") ?: return false
+ return runCatching { isDateTime(body) }.getOrDefault(false)
+ }
+
+ /**
+ * The colour a format code's section paints [raw] in — `[Red]`, `[Blue]`, `[Color10]` — as ARGB,
+ * or null when the section names none. `#,##0;[Red]-#,##0` is how most finance sheets show a loss.
+ */
+ fun colorFor(raw: String, code: String?): Int? {
+ if (code.isNullOrBlank() || !code.contains('[')) return null
+ val value = raw.trim().toDoubleOrNull() ?: return null
+ val sections = splitSections(code)
+ val section = when {
+ value < 0 && sections.size >= 2 -> sections[1]
+ value == 0.0 && sections.size >= 3 -> sections[2]
+ else -> sections[0]
+ }
+ val m = Regex("\\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow|Color\\s*(\\d+))]", RegexOption.IGNORE_CASE)
+ .find(section) ?: return null
+ return when (m.groupValues[1].lowercase().replace(" ", "").takeWhile { it.isLetter() }) {
+ "black" -> 0xFF000000.toInt()
+ "blue" -> 0xFF0000FF.toInt()
+ "cyan" -> 0xFF00FFFF.toInt()
+ "green" -> 0xFF00FF00.toInt()
+ "magenta" -> 0xFFFF00FF.toInt()
+ "red" -> 0xFFFF0000.toInt()
+ "white" -> 0xFFFFFFFF.toInt()
+ "yellow" -> 0xFFFFFF00.toInt()
+ else -> m.groupValues[2].toIntOrNull()?.let { com.chethan616.clearpdf.utils.xlsx.XlsxColors.indexed(it + 7) }
}
+ }
/**
* Render [raw] (the literal `<v>` text of a numeric cell) through [code].
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxColors.kt b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxColors.kt
new file mode 100644
index 0000000..543c907
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxColors.kt
@@ -0,0 +1,181 @@
+package com.chethan616.clearpdf.utils.xlsx
+
+import kotlin.math.abs
+import kotlin.math.roundToInt
+
+/**
+ * A SpreadsheetML colour as the file states it — `rgb`, `theme` (+ `tint`), `indexed`, or `auto` —
+ * kept in that form so a colour the user picked from the theme grid is written back as a theme
+ * reference (and follows a theme change in Excel) rather than being flattened to a literal.
+ */
+data class ColorSpec(
+ val rgb: Int? = null,
+ val theme: Int = -1,
+ val indexed: Int = -1,
+ val tint: Double = 0.0,
+ val auto: Boolean = false
+) {
+ /** ARGB, or null for "automatic" (the renderer picks the theme's ink). */
+ fun resolve(themeColors: IntArray, indexedColors: IntArray?): Int? {
+ val base: Int = when {
+ auto -> return null
+ rgb != null -> rgb
+ theme >= 0 -> themeColors.getOrNull(theme) ?: return null
+ indexed >= 0 -> {
+ if (indexed == 64 || indexed == 65) return null // system foreground/background
+ indexedColors?.getOrNull(indexed) ?: XlsxColors.indexed(indexed) ?: return null
+ }
+ else -> return null
+ }
+ val opaque = if ((base ushr 24) == 0) base or 0xFF000000.toInt() else base
+ return if (tint != 0.0) XlsxColors.applyTint(opaque, tint) else opaque
+ }
+
+ /** `<{tag} …/>` — the attribute form Excel writes. */
+ fun toXml(tag: String): String = buildString {
+ append('<').append(tag)
+ when {
+ auto -> append(" auto=\"1\"")
+ rgb != null -> append(" rgb=\"").append(XlsxColors.hex8(rgb)).append('"')
+ theme >= 0 -> append(" theme=\"").append(theme).append('"')
+ indexed >= 0 -> append(" indexed=\"").append(indexed).append('"')
+ }
+ if (tint != 0.0 && !auto) append(" tint=\"").append(tint.toString()).append('"')
+ append("/>")
+ }
+
+ companion object {
+ fun ofArgb(argb: Int) = ColorSpec(rgb = argb or 0xFF000000.toInt())
+
+ /** From a `<color>`/`<fgColor>` element's attributes. */
+ fun fromAttrs(a: Map<String, String>): ColorSpec? {
+ val tint = a["tint"]?.toDoubleOrNull() ?: 0.0
+ return when {
+ a["rgb"] != null -> XlsxColors.parseHex(a["rgb"]!!)?.let { ColorSpec(rgb = it, tint = tint) }
+ a["theme"] != null -> a["theme"]!!.toIntOrNull()?.let { ColorSpec(theme = it, tint = tint) }
+ a["indexed"] != null -> a["indexed"]!!.toIntOrNull()?.let { ColorSpec(indexed = it, tint = tint) }
+ a["auto"] == "1" || a["auto"] == "true" -> ColorSpec(auto = true)
+ else -> null
+ }
+ }
+ }
+}
+
+object XlsxColors {
+
+ /**
+ * Office 2013–2022 default theme, in *theme-index* order (lt1, dk1, lt2, dk2, accent1–6, hlink,
+ * folHlink). Used when a workbook has no theme part.
+ */
+ val DefaultTheme: IntArray = intArrayOf(
+ 0xFFFFFFFF.toInt(), 0xFF000000.toInt(), 0xFFE7E6E6.toInt(), 0xFF44546A.toInt(),
+ 0xFF4472C4.toInt(), 0xFFED7D31.toInt(), 0xFFA5A5A5.toInt(), 0xFFFFC000.toInt(),
+ 0xFF5B9BD5.toInt(), 0xFF70AD47.toInt(), 0xFF0563C1.toInt(), 0xFF954F72.toInt()
+ )
+
+ /** The legacy 64-colour palette `indexed="n"` points into (0–7 repeat 8–15). */
+ private val IndexedPalette = intArrayOf(
+ 0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,
+ 0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF,
+ 0x800000, 0x008000, 0x000080, 0x808000, 0x800080, 0x008080, 0xC0C0C0, 0x808080,
+ 0x9999FF, 0x993366, 0xFFFFCC, 0xCCFFFF, 0x660066, 0xFF8080, 0x0066CC, 0xCCCCFF,
+ 0x000080, 0xFF00FF, 0xFFFF00, 0x00FFFF, 0x800080, 0x800000, 0x008080, 0x0000FF,
+ 0x00CCFF, 0xCCFFFF, 0xCCFFCC, 0xFFFF99, 0x99CCFF, 0xFF99CC, 0xCC99FF, 0xFFCC99,
+ 0x3366FF, 0x33CCCC, 0x99CC00, 0xFFCC00, 0xFF9900, 0xFF6600, 0x666699, 0x969696,
+ 0x003366, 0x339966, 0x003300, 0x333300, 0x993300, 0x993366, 0x333399, 0x333333
+ )
+
+ fun indexed(i: Int): Int? = IndexedPalette.getOrNull(i)?.let { it or 0xFF000000.toInt() }
+
+ fun parseHex(s: String): Int? {
+ val h = s.trim().removePrefix("#")
+ val v = h.toLongOrNull(16) ?: return null
+ return when (h.length) {
+ 8 -> v.toInt()
+ 6 -> (v or 0xFF000000L).toInt()
+ else -> null
+ }
+ }
+
+ fun hex8(argb: Int): String = String.format(java.util.Locale.ROOT, "%08X", argb)
+ fun hex6(argb: Int): String = String.format(java.util.Locale.ROOT, "%06X", argb and 0xFFFFFF)
+
+ /**
+ * Excel's tint: in HLS, `tint < 0` darkens (`L·(1+tint)`), `tint > 0` lightens
+ * (`L·(1−tint) + tint`). Hue and saturation stay; alpha is preserved.
+ */
+ fun applyTint(argb: Int, tint: Double): Int {
+ if (tint == 0.0) return argb
+ val hls = rgbToHls(argb)
+ val l = if (tint < 0) hls[2] * (1.0 + tint) else hls[2] * (1.0 - tint) + tint
+ return (argb and 0xFF000000.toInt()) or (hlsToRgb(hls[0], l.coerceIn(0.0, 1.0), hls[1]) and 0xFFFFFF)
+ }
+
+ /** [h (0–1), s, l] for an ARGB int. */
+ fun rgbToHls(argb: Int): DoubleArray {
+ val r = ((argb shr 16) and 0xFF) / 255.0
+ val g = ((argb shr 8) and 0xFF) / 255.0
+ val b = (argb and 0xFF) / 255.0
+ val max = maxOf(r, g, b)
+ val min = minOf(r, g, b)
+ val l = (max + min) / 2
+ if (max == min) return doubleArrayOf(0.0, 0.0, l)
+ val d = max - min
+ val s = if (l > 0.5) d / (2 - max - min) else d / (max + min)
+ val h = when (max) {
+ r -> ((g - b) / d + (if (g < b) 6 else 0)) / 6
+ g -> ((b - r) / d + 2) / 6
+ else -> ((r - g) / d + 4) / 6
+ }
+ return doubleArrayOf(h, s, l)
+ }
+
+ fun hlsToRgb(h: Double, l: Double, s: Double): Int {
+ if (s == 0.0) {
+ val v = (l * 255).roundToInt().coerceIn(0, 255)
+ return 0xFF000000.toInt() or (v shl 16) or (v shl 8) or v
+ }
+ val q = if (l < 0.5) l * (1 + s) else l + s - l * s
+ val p = 2 * l - q
+ fun hue(tIn: Double): Double {
+ var t = tIn
+ if (t < 0) t += 1.0
+ if (t > 1) t -= 1.0
+ return when {
+ t < 1.0 / 6 -> p + (q - p) * 6 * t
+ t < 0.5 -> q
+ t < 2.0 / 3 -> p + (q - p) * (2.0 / 3 - t) * 6
+ else -> p
+ }
+ }
+ val r = (hue(h + 1.0 / 3) * 255).roundToInt().coerceIn(0, 255)
+ val g = (hue(h) * 255).roundToInt().coerceIn(0, 255)
+ val b = (hue(h - 1.0 / 3) * 255).roundToInt().coerceIn(0, 255)
+ return 0xFF000000.toInt() or (r shl 16) or (g shl 8) or b
+ }
+
+ /** Perceived luminance 0–1, for picking legible ink over a fill. */
+ fun luminance(argb: Int): Double {
+ val r = ((argb shr 16) and 0xFF) / 255.0
+ val g = ((argb shr 8) and 0xFF) / 255.0
+ val b = (argb and 0xFF) / 255.0
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
+ }
+
+ /** The tints Excel's colour grid shows under each theme swatch (rows 2–6). */
+ fun themeGridTints(baseArgb: Int): DoubleArray {
+ val l = rgbToHls(baseArgb)[2]
+ return when {
+ l < 0.02 -> doubleArrayOf(0.4999, 0.3499, 0.2499, 0.1499, 0.0499) // black
+ l > 0.98 -> doubleArrayOf(-0.0499, -0.1499, -0.2499, -0.3499, -0.4999) // white
+ l < 0.2 -> doubleArrayOf(0.8999, 0.7499, 0.4999, 0.2499, 0.0999)
+ l > 0.8 -> doubleArrayOf(-0.0999, -0.2499, -0.4999, -0.7499, -0.8999)
+ else -> doubleArrayOf(0.7999, 0.5999, 0.3999, -0.2499, -0.4999)
+ }
+ }
+
+ internal fun near(a: Int, b: Int, tol: Int = 1): Boolean =
+ abs(((a shr 16) and 0xFF) - ((b shr 16) and 0xFF)) <= tol &&
+ abs(((a shr 8) and 0xFF) - ((b shr 8) and 0xFF)) <= tol &&
+ abs((a and 0xFF) - (b and 0xFF)) <= tol
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxModel.kt b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxModel.kt
new file mode 100644
index 0000000..c9e9b87
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxModel.kt
@@ -0,0 +1,204 @@
+package com.chethan616.clearpdf.utils.xlsx
+
+import com.chethan616.clearpdf.utils.ExcelCellFormat
+
+/** A styled stretch of a rich-text string: [start, end) with the run's `rPr`. */
+class TextRun(val start: Int, val end: Int, val props: XmlEl?)
+
+/** A shared/inline string: its plain text plus, when rich, the formatted runs. */
+class RichText(val text: String, val runs: List<TextRun>?) {
+ val isRich get() = runs != null && runs.size > 1
+}
+
+/** A cell's `<f>` element. [text] is empty for a shared-formula follower. */
+data class FormulaSpec(val text: String, val type: String? = null, val si: String? = null, val ref: String? = null)
+
+/**
+ * One cell's stored content. [type] is the `t` attribute ("" for numeric, "s", "str", "inlineStr",
+ * "b", "e"); [raw] the `<v>` text (for "s", the shared-string index; for inline strings the text).
+ */
+data class CellData(
+ val type: String,
+ val raw: String,
+ val style: Int,
+ val formula: FormulaSpec? = null,
+ val rich: RichText? = null
+) {
+ val isBlank get() = raw.isEmpty() && formula == null
+}
+
+class RowData(
+ var heightPt: Float? = null,
+ var hidden: Boolean = false,
+ var style: Int = -1
+) {
+ val cells = java.util.TreeMap<Int, CellData>()
+}
+
+data class ColumnInfo(val widthChars: Float?, val hidden: Boolean, val style: Int)
+
+enum class ValidationKind { LIST, OTHER }
+
+class DataValidation(
+ var ranges: List<CellRange>,
+ val kind: ValidationKind,
+ /** `formula1` as written: `"a,b,c"` (quoted list) or a range such as `Sheet2!$A$1:$A$9`. */
+ val formula1: String?,
+ val allowBlank: Boolean,
+ val showDropDown: Boolean,
+ val strict: Boolean,
+ val prompt: String?
+)
+
+/**
+ * The editable in-memory form of one worksheet. Rows/cols are 0-based. Unlike the older
+ * [com.chethan616.clearpdf.utils.SpreadsheetParser.Sheet], nothing is folded away — hidden rows and
+ * columns keep their indices (and simply render at zero size), so every edit maps straight back to
+ * the reference it has in the file.
+ */
+class XlsxSheet(
+ val name: String,
+ /** Zip path of this sheet's part, e.g. `xl/worksheets/sheet1.xml`. */
+ val partPath: String
+) {
+ val rows = java.util.TreeMap<Int, RowData>()
+ val cols = java.util.TreeMap<Int, ColumnInfo>()
+ val merges = mutableListOf<CellRange>()
+ val validations = mutableListOf<DataValidation>()
+ var defaultRowHeightPt = 15f
+ var defaultColWidthChars = 8.43f
+ var frozenRows = 0
+ var frozenCols = 0
+ var showGridLines = true
+ var tabColor: ColorSpec? = null
+ var hidden = false
+ /** True when the reader stopped early (row cap). The grid shows what it has. */
+ var truncated = false
+
+ fun cell(r: Int, c: Int): CellData? = rows[r]?.cells?.get(c)
+
+ val maxRow: Int get() = rows.lastEntry()?.let { e -> if (e.value.cells.isEmpty() && e.value.heightPt == null) lastRealRow() else e.key } ?: -1
+ private fun lastRealRow(): Int = rows.descendingMap().entries.firstOrNull { it.value.cells.isNotEmpty() }?.key ?: -1
+ val maxCol: Int get() {
+ var m = -1
+ for (row in rows.values) row.cells.lastEntry()?.let { if (it.key > m) m = it.key }
+ for (mr in merges) if (mr.c2 > m) m = mr.c2
+ return m
+ }
+
+ fun isRowHidden(r: Int) = rows[r]?.hidden == true
+ fun isColHidden(c: Int) = cols[c]?.hidden == true
+
+ fun rowHeightPt(r: Int): Float {
+ val row = rows[r]
+ if (row?.hidden == true) return 0f
+ return row?.heightPt ?: defaultRowHeightPt
+ }
+
+ fun colWidthChars(c: Int): Float {
+ val ci = cols[c]
+ if (ci?.hidden == true) return 0f
+ return ci?.widthChars ?: defaultColWidthChars
+ }
+
+ /** The merge whose top-left is (r, c), or that covers it. */
+ fun mergeAt(r: Int, c: Int): CellRange? {
+ for (m in merges) if (m.contains(r, c)) return m
+ return null
+ }
+
+ fun validationAt(r: Int, c: Int): DataValidation? =
+ validations.firstOrNull { v -> v.ranges.any { it.contains(r, c) } }
+}
+
+class XlsxWorkbook(
+ val sheets: List<XlsxSheet>,
+ val styles: StyleTable,
+ val sharedStrings: List<RichText>,
+ /** True for a genuine .xlsx package that can be patched and saved. */
+ val editable: Boolean
+) {
+ fun sheetByName(name: String): XlsxSheet? = sheets.firstOrNull { it.name.equals(name, ignoreCase = true) }
+
+ fun textOf(c: CellData): RichText? = when (c.type) {
+ "s" -> sharedStrings.getOrNull(c.raw.trim().toIntOrNull() ?: -1)
+ "inlineStr" -> c.rich ?: RichText(c.raw, null)
+ else -> null
+ }
+
+ /** What the cell shows: formatted number/date, text, TRUE/FALSE or the error code. */
+ fun display(c: CellData): String = when (c.type) {
+ "s", "inlineStr" -> textOf(c)?.text ?: c.raw
+ "b" -> if (c.raw.trim() == "1") "TRUE" else "FALSE"
+ "str", "e" -> c.raw
+ else -> if (c.raw.isEmpty()) "" else ExcelCellFormat.apply(c.raw, styles.resolve(c.style).numFmtCode)
+ }
+
+ /** What the formula bar shows for editing. */
+ fun editText(c: CellData): String = when {
+ c.formula != null && c.formula.text.isNotEmpty() -> "=" + c.formula.text
+ c.type == "s" || c.type == "inlineStr" -> textOf(c)?.text ?: c.raw
+ c.type == "b" -> if (c.raw.trim() == "1") "TRUE" else "FALSE"
+ c.type == "" && ExcelCellFormat.isDateCode(styles.resolve(c.style).numFmtCode) -> display(c)
+ else -> c.raw
+ }
+
+ /** Items for a list validation: an inline list or the values of the range it names. */
+ fun listItems(v: DataValidation, host: XlsxSheet): List<String> {
+ val f = v.formula1?.trim() ?: return emptyList()
+ if (f.startsWith("\"")) {
+ return f.removeSurrounding("\"").split(',').map { it.trim() }.filter { it.isNotEmpty() }
+ }
+ val bang = f.lastIndexOf('!')
+ val sheet = if (bang > 0) sheetByName(f.substring(0, bang).removePrefix("=").removeSurrounding("'").replace("''", "'")) else host
+ val range = XlsxRefs.parseRange(f.removePrefix("=")) ?: return emptyList()
+ sheet ?: return emptyList()
+ val out = ArrayList<String>()
+ val rLast = minOf(range.r2, sheet.rows.lastKey() ?: range.r1, range.r1 + 500)
+ for (r in range.r1..rLast) for (c in range.c1..minOf(range.c2, range.c1 + 50)) {
+ sheet.cell(r, c)?.let { cd -> display(cd).takeIf { it.isNotBlank() }?.let(out::add) }
+ }
+ return out.distinct()
+ }
+
+ /**
+ * Turn typed text into stored cell content, keeping [style]. Numbers stay numbers, TRUE/FALSE
+ * become booleans, a leading `=` becomes a formula (Excel recalculates it on open), a date
+ * typed into a date-formatted cell becomes its serial, everything else is inline text.
+ */
+ fun parseInput(text: String, style: Int): CellData? {
+ if (text.isEmpty()) return null
+ if (text.startsWith("=") && text.length > 1) return CellData("", "", style, FormulaSpec(text.substring(1)))
+ val trimmed = text.trim()
+ val upper = trimmed.uppercase()
+ if (upper == "TRUE" || upper == "FALSE") return CellData("b", if (upper == "TRUE") "1" else "0", style)
+ val code = styles.resolve(style).numFmtCode
+ if (code != "@") {
+ val num = parseNumber(trimmed)
+ if (num != null) return CellData("", num, style)
+ if (ExcelCellFormat.isDateCode(code)) parseDateSerial(trimmed)?.let { return CellData("", it, style) }
+ }
+ return CellData("inlineStr", text, style)
+ }
+
+ private fun parseNumber(s: String): String? {
+ var t = s.replace(",", "")
+ var pct = false
+ if (t.endsWith("%")) { pct = true; t = t.dropLast(1) }
+ val d = t.toDoubleOrNull() ?: return null
+ if (d.isNaN() || d.isInfinite()) return null
+ val v = if (pct) d / 100 else d
+ return if (v == Math.floor(v) && kotlin.math.abs(v) < 1e15) v.toLong().toString() else v.toString()
+ }
+
+ private fun parseDateSerial(s: String): String? {
+ val m = Regex("^(\\d{1,4})[-/.](\\d{1,2})[-/.](\\d{1,4})$").find(s) ?: return null
+ val (a, b, c) = m.destructured
+ val (y, mo, d) = if (a.length == 4) Triple(a.toInt(), b.toInt(), c.toInt()) else Triple(c.toInt().let { if (it < 100) it + 2000 else it }, b.toInt(), a.toInt())
+ if (mo !in 1..12 || d !in 1..31) return null
+ val cal = java.util.GregorianCalendar(java.util.TimeZone.getTimeZone("UTC")).apply { clear(); set(y, mo - 1, d) }
+ val base = java.util.GregorianCalendar(java.util.TimeZone.getTimeZone("UTC")).apply { clear(); set(1899, 11, 30) }
+ val days = (cal.timeInMillis - base.timeInMillis) / 86_400_000L
+ return days.toString()
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxRefs.kt b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxRefs.kt
new file mode 100644
index 0000000..6bc43de
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxRefs.kt
@@ -0,0 +1,245 @@
+package com.chethan616.clearpdf.utils.xlsx
+
+/** 0-based, inclusive cell range. */
+data class CellRange(val r1: Int, val c1: Int, val r2: Int, val c2: Int) {
+ fun contains(r: Int, c: Int) = r in r1..r2 && c in c1..c2
+ val isSingle get() = r1 == r2 && c1 == c2
+ fun toRef(): String =
+ if (isSingle) XlsxRefs.cellRef(r1, c1) else XlsxRefs.cellRef(r1, c1) + ":" + XlsxRefs.cellRef(r2, c2)
+
+ companion object {
+ fun of(r1: Int, c1: Int, r2: Int, c2: Int) = CellRange(minOf(r1, r2), minOf(c1, c2), maxOf(r1, r2), maxOf(c1, c2))
+ }
+}
+
+/** Which axis a structural edit moves along. */
+enum class Axis { ROW, COL }
+
+/**
+ * A1-reference helpers, plus the shifting that inserting/deleting rows or columns needs across
+ * every place a sheet names its own cells (`sqref`, `ref`, merges, formulas).
+ */
+object XlsxRefs {
+ const val MaxRow = 1_048_575
+ const val MaxCol = 16_383
+
+ fun colLetter(index: Int): String {
+ var i = index
+ val sb = StringBuilder()
+ while (i >= 0) { sb.insert(0, 'A' + (i % 26)); i = i / 26 - 1 }
+ return sb.toString()
+ }
+
+ fun colIndex(letters: String): Int {
+ var idx = 0
+ for (ch in letters) {
+ val up = ch.uppercaseChar()
+ if (up !in 'A'..'Z') return -1
+ idx = idx * 26 + (up - 'A' + 1)
+ }
+ return idx - 1
+ }
+
+ fun cellRef(r: Int, c: Int) = colLetter(c) + (r + 1)
+
+ /** "B7" / "$B$7" → (6, 1); null when malformed. */
+ fun parseCell(ref: String): Pair<Int, Int>? {
+ val s = ref.replace("$", "")
+ var i = 0
+ while (i < s.length && s[i].isLetter()) i++
+ if (i == 0 || i == s.length) return null
+ val c = colIndex(s.substring(0, i))
+ val r = s.substring(i).toIntOrNull() ?: return null
+ if (c < 0 || r < 1) return null
+ return (r - 1) to c
+ }
+
+ /** "A1:C3" or "B2" → range; also whole columns "A:C" and rows "2:5". */
+ fun parseRange(ref: String): CellRange? {
+ val s = ref.substringAfterLast('!').replace("$", "").trim()
+ val parts = s.split(':')
+ if (parts.size == 1) return parseCell(parts[0])?.let { (r, c) -> CellRange(r, c, r, c) }
+ if (parts.size != 2) return null
+ val a = parts[0]; val b = parts[1]
+ if (a.all { it.isLetter() } && b.all { it.isLetter() }) {
+ val c1 = colIndex(a); val c2 = colIndex(b)
+ if (c1 < 0 || c2 < 0) return null
+ return CellRange.of(0, c1, MaxRow, c2)
+ }
+ if (a.all { it.isDigit() } && b.all { it.isDigit() }) {
+ val r1 = a.toInt() - 1; val r2 = b.toInt() - 1
+ return CellRange.of(r1, 0, r2, MaxCol)
+ }
+ val p1 = parseCell(a) ?: return null
+ val p2 = parseCell(b) ?: return null
+ return CellRange.of(p1.first, p1.second, p2.first, p2.second)
+ }
+
+ fun parseSqref(sqref: String): List<CellRange> =
+ sqref.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.mapNotNull { parseRange(it) }
+
+ /**
+ * Shift a range for [count] rows/cols inserted (count > 0) or deleted (count < 0) at [at].
+ * Returns null when a deletion swallows the whole range.
+ */
+ fun shiftRange(range: CellRange, axis: Axis, at: Int, count: Int): CellRange? {
+ val (lo, hi) = if (axis == Axis.ROW) range.r1 to range.r2 else range.c1 to range.c2
+ val max = if (axis == Axis.ROW) MaxRow else MaxCol
+ val nl: Int
+ val nh: Int
+ if (count > 0) {
+ // Whole-row / whole-column spans stay whole.
+ if (lo == 0 && hi == max) return range
+ nl = if (lo >= at) lo + count else lo
+ nh = if (hi >= at) (hi + count).coerceAtMost(max) else hi
+ } else {
+ val n = -count
+ val delEnd = at + n - 1
+ if (lo >= at && hi <= delEnd) return null
+ if (lo == 0 && hi == max) return range
+ nl = when {
+ lo < at -> lo
+ lo <= delEnd -> at
+ else -> lo - n
+ }
+ nh = when {
+ hi < at -> hi
+ hi <= delEnd -> at - 1
+ else -> hi - n
+ }
+ if (nh < nl) return null
+ }
+ return if (axis == Axis.ROW) range.copy(r1 = nl, r2 = nh) else range.copy(c1 = nl, c2 = nh)
+ }
+
+ /** Shift every range in a space-separated `sqref`; null when none survive. */
+ fun shiftSqref(sqref: String, axis: Axis, at: Int, count: Int): String? {
+ val out = parseSqref(sqref).mapNotNull { shiftRange(it, axis, at, count) }
+ return if (out.isEmpty()) null else out.joinToString(" ") { it.toRef() }
+ }
+
+ /**
+ * Shift the A1 references inside a formula. References qualified with another sheet are left
+ * alone unless [sheetName] matches; unqualified ones move only when [formulaOnSameSheet].
+ * A reference a deletion removes becomes `#REF!`, as Excel does.
+ */
+ fun shiftFormula(
+ formula: String,
+ sheetName: String,
+ formulaOnSameSheet: Boolean,
+ axis: Axis,
+ at: Int,
+ count: Int
+ ): String {
+ val out = StringBuilder()
+ var i = 0
+ val n = formula.length
+ while (i < n) {
+ val ch = formula[i]
+ if (ch == '"') { // string literal — copy verbatim
+ val start = i
+ i++
+ while (i < n) {
+ if (formula[i] == '"') {
+ if (i + 1 < n && formula[i + 1] == '"') { i += 2; continue }
+ i++; break
+ }
+ i++
+ }
+ out.append(formula, start, i)
+ continue
+ }
+ val m = if (i == 0 || !(formula[i - 1].isLetterOrDigit() || formula[i - 1] in "_.$'")) RefToken.matchAt(formula, i) else null
+ if (m == null) { out.append(ch); i++; continue }
+ val prev = if (m.range.first > 0) formula[m.range.first - 1] else ' '
+ val next = if (m.range.last + 1 < n) formula[m.range.last + 1] else ' '
+ val token = m.value
+ val boundaryOk = !(prev.isLetterOrDigit() || prev == '_' || prev == '.' || prev == '$') &&
+ !(next.isLetterOrDigit() || next == '_' || next == '(' || next == '!')
+ if (!boundaryOk) {
+ out.append(ch)
+ i++
+ continue
+ }
+ val bang = token.lastIndexOf('!')
+ val qualifier = if (bang >= 0) token.substring(0, bang) else null
+ val refPart = if (bang >= 0) token.substring(bang + 1) else token
+ val applies = if (qualifier == null) formulaOnSameSheet else {
+ qualifier.removeSurrounding("'").replace("''", "'").equals(sheetName, ignoreCase = true)
+ }
+ if (!applies) {
+ out.append(token)
+ } else {
+ val shifted = shiftRefText(refPart, axis, at, count)
+ if (qualifier != null) out.append(qualifier).append('!')
+ out.append(shifted)
+ }
+ i = m.range.last + 1
+ }
+ return out.toString()
+ }
+
+ private val RefToken = Regex(
+ "(?:(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!)?" +
+ "(?:\\$?[A-Za-z]{1,3}\\$?[0-9]{1,7}(?::\\$?[A-Za-z]{1,3}\\$?[0-9]{1,7})?" +
+ "|\\$?[A-Za-z]{1,3}:\\$?[A-Za-z]{1,3}" +
+ "|\\$?[0-9]{1,7}:\\$?[0-9]{1,7})"
+ )
+
+ /** One reference ("$A$1", "A1:B2", "A:C", "3:5") shifted, keeping `$` markers. */
+ private fun shiftRefText(ref: String, axis: Axis, at: Int, count: Int): String {
+ val parts = ref.split(':')
+ data class P(val colAbs: Boolean, val col: Int, val rowAbs: Boolean, val row: Int) // -1 = absent
+ fun parse(p: String): P? {
+ var i = 0
+ var colAbs = false
+ var rowAbs = false
+ if (i < p.length && p[i] == '$') { colAbs = true; i++ }
+ val cs = i
+ while (i < p.length && p[i].isLetter()) i++
+ val letters = p.substring(cs, i)
+ if (i < p.length && p[i] == '$') { rowAbs = true; i++ }
+ val digits = p.substring(i)
+ if (letters.isEmpty() && colAbs && digits.isNotEmpty()) { rowAbs = true; colAbs = false }
+ if (digits.isNotEmpty() && !digits.all { it.isDigit() }) return null
+ val col = if (letters.isEmpty()) -1 else colIndex(letters)
+ val row = if (digits.isEmpty()) -1 else digits.toInt() - 1
+ if (col < -1 || col > MaxCol) return null
+ return P(colAbs, col, rowAbs, row)
+ }
+ fun fmt(p: P): String = buildString {
+ if (p.col >= 0) { if (p.colAbs) append('$'); append(colLetter(p.col)) }
+ if (p.row >= 0) { if (p.rowAbs) append('$'); append(p.row + 1) }
+ }
+ val ps = parts.map { parse(it) ?: return ref }
+ val v = ps.map { if (axis == Axis.ROW) it.row else it.col }
+ if (v.any { it < 0 }) return ref // whole rows when shifting columns, etc.
+ val lo = v.first()
+ val hi = v.last()
+ val range = if (axis == Axis.ROW) CellRange(lo, 0, hi, 0) else CellRange(0, lo, 0, hi)
+ val shifted = shiftRange(range, axis, at, count) ?: return "#REF!"
+ val nlo = if (axis == Axis.ROW) shifted.r1 else shifted.c1
+ val nhi = if (axis == Axis.ROW) shifted.r2 else shifted.c2
+ return if (ps.size == 1) {
+ fmt(if (axis == Axis.ROW) ps[0].copy(row = nlo) else ps[0].copy(col = nlo))
+ } else {
+ val a = if (axis == Axis.ROW) ps[0].copy(row = nlo) else ps[0].copy(col = nlo)
+ val b = if (axis == Axis.ROW) ps[1].copy(row = nhi) else ps[1].copy(col = nhi)
+ fmt(a) + ":" + fmt(b)
+ }
+ }
+
+ fun escapeXml(s: String): String {
+ val sb = StringBuilder(s.length + 8)
+ for (ch in s) {
+ when (ch) {
+ '&' -> sb.append("&amp;")
+ '<' -> sb.append("&lt;")
+ '>' -> sb.append("&gt;")
+ '"' -> sb.append("&quot;")
+ else -> if (ch.code < 0x20 && ch != '\n' && ch != '\t' && ch != '\r') Unit else sb.append(ch)
+ }
+ }
+ return sb.toString()
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxStyles.kt b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxStyles.kt
new file mode 100644
index 0000000..49631c8
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/utils/xlsx/XlsxStyles.kt
@@ -0,0 +1,358 @@
+package com.chethan616.clearpdf.utils.xlsx
+
+import com.chethan616.clearpdf.utils.ExcelCellFormat
+
+/**
+ * A tiny lossless element tree for the pieces of `styles.xml` we derive new entries from. Keeping
+ * every attribute and child (not just the ones we understand) means a font we clone to make bold
+ * still carries its charset, family, scheme and anything else the author's Excel put there.
+ * Names are stored without their namespace prefix.
+ */
+class XmlEl(
+ val name: String,
+ val attrs: LinkedHashMap<String, String> = LinkedHashMap(),
+ val children: MutableList<XmlEl> = mutableListOf(),
+ var text: String? = null
+) {
+ fun child(n: String): XmlEl? = children.firstOrNull { it.name == n }
+ fun copy(): XmlEl = XmlEl(name, LinkedHashMap(attrs), children.mapTo(mutableListOf()) { it.copy() }, text)
+
+ fun setChild(el: XmlEl) {
+ val i = children.indexOfFirst { it.name == el.name }
+ if (i >= 0) children[i] = el else children.add(el)
+ }
+
+ fun removeChild(n: String) { children.removeAll { it.name == n } }
+
+ fun toXml(prefix: String, sb: StringBuilder = StringBuilder()): StringBuilder {
+ sb.append('<').append(prefix).append(name)
+ for ((k, v) in attrs) sb.append(' ').append(k).append("=\"").append(XlsxRefs.escapeXml(v)).append('"')
+ if (children.isEmpty() && text == null) return sb.append("/>")
+ sb.append('>')
+ text?.let { sb.append(XlsxRefs.escapeXml(it)) }
+ for (c in children) c.toXml(prefix, sb)
+ return sb.append("</").append(prefix).append(name).append('>')
+ }
+}
+
+/** One border edge as the renderer needs it. `weight` 0 = none. */
+data class EdgeStyle(val weight: Float, val dashed: Boolean, val double: Boolean, val argb: Int?)
+
+/** Everything the renderer needs from one `cellXfs` entry, with colours already resolved. */
+class ResolvedStyle(
+ val fillArgb: Int?,
+ val fontArgb: Int?,
+ val bold: Boolean,
+ val italic: Boolean,
+ val underline: Boolean,
+ val doubleUnderline: Boolean,
+ val strike: Boolean,
+ val sizePt: Float,
+ val fontName: String?,
+ val left: EdgeStyle?,
+ val right: EdgeStyle?,
+ val top: EdgeStyle?,
+ val bottom: EdgeStyle?,
+ /** general, left, center, right, fill, justify, centerContinuous, distributed */
+ val hAlign: String,
+ /** top, center, bottom (default), justify, distributed */
+ val vAlign: String,
+ val wrap: Boolean,
+ val indent: Int,
+ val rotation: Int,
+ val numFmtId: Int,
+ val numFmtCode: String,
+ val superscript: Boolean = false,
+ val subscript: Boolean = false
+) {
+ companion object {
+ val Default = ResolvedStyle(
+ null, null, false, false, false, false, false, 11f, null,
+ null, null, null, null, "general", "bottom", false, 0, 0, 0, "General"
+ )
+ }
+}
+
+/** A formatting change requested from the toolbar. Null fields mean "leave as is". */
+data class StylePatch(
+ val bold: Boolean? = null,
+ val italic: Boolean? = null,
+ val underline: Boolean? = null,
+ val strike: Boolean? = null,
+ val fontSize: Double? = null,
+ val fontColor: ColorSpec? = null,
+ /** A solid fill colour, or [clearFill] to remove any fill. */
+ val fill: ColorSpec? = null,
+ val clearFill: Boolean = false,
+ val hAlign: String? = null,
+ val vAlign: String? = null,
+ val wrap: Boolean? = null,
+ val numFmtCode: String? = null,
+ /** Edge updates: null = untouched; a side with `style == null` clears it. */
+ val left: BorderSide? = null,
+ val right: BorderSide? = null,
+ val top: BorderSide? = null,
+ val bottom: BorderSide? = null
+) {
+ val touchesFont get() = bold != null || italic != null || underline != null || strike != null || fontSize != null || fontColor != null
+ val touchesFill get() = fill != null || clearFill
+ val touchesBorder get() = left != null || right != null || top != null || bottom != null
+ val touchesAlignment get() = hAlign != null || vAlign != null || wrap != null
+}
+
+/** `style` is a SpreadsheetML border style name ("thin", "medium", "dashed", "double" …) or null for none. */
+data class BorderSide(val style: String?, val color: ColorSpec? = null)
+
+/**
+ * The workbook's style sheet: the original entries (by index, exactly as read) plus any the user's
+ * edits appended. The writer emits only the appended tail, so the original indices never move and
+ * every untouched cell keeps pointing at the same `xf` it always did.
+ */
+class StyleTable(
+ val fonts: MutableList<XmlEl>,
+ val fills: MutableList<XmlEl>,
+ val borders: MutableList<XmlEl>,
+ val cellXfs: MutableList<XmlEl>,
+ val numFmts: MutableMap<Int, String>,
+ val themeColors: IntArray,
+ val indexedColors: IntArray?,
+ /** `cellStyleXfs` count, only so a derived `xf` can keep a valid `xfId`. */
+ val cellStyleXfCount: Int,
+ val hasStylesPart: Boolean
+) {
+ val origFonts = fonts.size
+ val origFills = fills.size
+ val origBorders = borders.size
+ val origXfs = cellXfs.size
+ val origNumFmtIds: Set<Int> = numFmts.keys.toSet()
+
+ private var resolved = arrayOfNulls<ResolvedStyle>(cellXfs.size)
+ private val derived = HashMap<Pair<Int, StylePatch>, Int>()
+
+ val xfCount get() = cellXfs.size
+
+ fun resolve(xf: Int): ResolvedStyle {
+ if (xf < 0 || xf >= cellXfs.size) return if (cellXfs.isNotEmpty() && xf != 0) resolve(0) else ResolvedStyle.Default
+ if (resolved.size < cellXfs.size) resolved = resolved.copyOf(cellXfs.size)
+ resolved[xf]?.let { return it }
+ return buildResolved(cellXfs[xf]).also { resolved[xf] = it }
+ }
+
+ fun numFmtCode(id: Int): String = ExcelCellFormat.codeFor(id, numFmts)
+
+ fun color(el: XmlEl?): Int? = el?.let { ColorSpec.fromAttrs(it.attrs)?.resolve(themeColors, indexedColors) }
+
+ private fun buildResolved(xf: XmlEl): ResolvedStyle {
+ val font = fonts.getOrNull(xf.attrs["fontId"]?.toIntOrNull() ?: 0)
+ val fill = fills.getOrNull(xf.attrs["fillId"]?.toIntOrNull() ?: 0)
+ val border = borders.getOrNull(xf.attrs["borderId"]?.toIntOrNull() ?: 0)
+ val align = xf.child("alignment")
+ val numFmtId = xf.attrs["numFmtId"]?.toIntOrNull() ?: 0
+ val f = FontFacts.of(font, this)
+ return ResolvedStyle(
+ fillArgb = fillColor(fill),
+ fontArgb = f.argb,
+ bold = f.bold, italic = f.italic, underline = f.underline, doubleUnderline = f.doubleUnderline,
+ strike = f.strike, sizePt = f.size, fontName = f.name,
+ left = edge(border?.child("left") ?: border?.child("start")),
+ right = edge(border?.child("right") ?: border?.child("end")),
+ top = edge(border?.child("top")),
+ bottom = edge(border?.child("bottom")),
+ hAlign = align?.attrs?.get("horizontal") ?: "general",
+ vAlign = align?.attrs?.get("vertical") ?: "bottom",
+ wrap = align?.attrs?.get("wrapText").isTrue(),
+ indent = align?.attrs?.get("indent")?.toIntOrNull() ?: 0,
+ rotation = align?.attrs?.get("textRotation")?.toIntOrNull() ?: 0,
+ numFmtId = numFmtId,
+ numFmtCode = numFmtCode(numFmtId),
+ superscript = f.vertAlign == "superscript",
+ subscript = f.vertAlign == "subscript"
+ )
+ }
+
+ private fun fillColor(fill: XmlEl?): Int? {
+ fill ?: return null
+ fill.child("patternFill")?.let { p ->
+ val type = p.attrs["patternType"] ?: if (p.child("fgColor") != null) "solid" else "none"
+ if (type == "none") return null
+ val fg = color(p.child("fgColor"))
+ val bg = color(p.child("bgColor"))
+ return when (type) {
+ "solid" -> fg ?: bg
+ "gray125", "gray0625" -> 0xFFEFEFEF.toInt()
+ // Patterned fills are approximated by their foreground, softened — a hatch at cell
+ // scale on a phone reads as a flat tone anyway.
+ else -> fg?.let { blend(it, bg ?: 0xFFFFFFFF.toInt(), 0.5f) } ?: bg
+ }
+ }
+ fill.child("gradientFill")?.let { g ->
+ return color(g.children.firstOrNull { it.name == "stop" }?.child("color"))
+ }
+ return null
+ }
+
+ private fun edge(side: XmlEl?): EdgeStyle? {
+ val style = side?.attrs?.get("style") ?: return null
+ if (style == "none") return null
+ val w = when (style) {
+ "medium", "mediumDashed", "mediumDashDot", "mediumDashDotDot", "slantDashDot" -> 2f
+ "thick" -> 3f
+ "double" -> 3f
+ "hair" -> 0.5f
+ else -> 1f
+ }
+ return EdgeStyle(w, style.contains("ash") || style.contains("otted") || style == "hair", style == "double", color(side.child("color")))
+ }
+
+ // ── Deriving new styles ────────────────────────────────────────────────────
+
+ /** The `cellXfs` index for [base] with [patch] applied — appended once, then reused. */
+ fun derive(base: Int, patch: StylePatch): Int {
+ val b = if (base in 0 until cellXfs.size) base else 0
+ derived[b to patch]?.let { return it }
+ if (cellXfs.isEmpty()) {
+ // A styles part with no cellXfs (or none at all): seed Excel's defaults.
+ if (fonts.isEmpty()) fonts.add(defaultFont())
+ if (fills.isEmpty()) { fills.add(patternFill("none")); fills.add(patternFill("gray125")) }
+ if (borders.isEmpty()) borders.add(emptyBorder())
+ cellXfs.add(XmlEl("xf", linkedMapOf("numFmtId" to "0", "fontId" to "0", "fillId" to "0", "borderId" to "0", "xfId" to "0")))
+ }
+ val xf = cellXfs[b].copy()
+ if (patch.touchesFont) {
+ val font = (fonts.getOrNull(xf.attrs["fontId"]?.toIntOrNull() ?: 0) ?: defaultFont()).copy()
+ patch.bold?.let { setFlag(font, "b", it) }
+ patch.italic?.let { setFlag(font, "i", it) }
+ patch.strike?.let { setFlag(font, "strike", it) }
+ patch.underline?.let { if (it) font.setChild(XmlEl("u")) else font.removeChild("u") }
+ patch.fontSize?.let { font.setChild(XmlEl("sz", linkedMapOf("val" to trimNum(it)))) }
+ patch.fontColor?.let { font.setChild(colorEl("color", it)) }
+ fonts.add(font)
+ xf.attrs["fontId"] = (fonts.size - 1).toString()
+ xf.attrs["applyFont"] = "1"
+ }
+ if (patch.touchesFill) {
+ val fill = if (patch.clearFill || patch.fill == null) patternFill("none") else XmlEl(
+ "fill", children = mutableListOf(
+ XmlEl("patternFill", linkedMapOf("patternType" to "solid"), mutableListOf(colorEl("fgColor", patch.fill), XmlEl("bgColor", linkedMapOf("indexed" to "64"))))
+ )
+ )
+ fills.add(fill)
+ xf.attrs["fillId"] = (fills.size - 1).toString()
+ xf.attrs["applyFill"] = "1"
+ }
+ if (patch.touchesBorder) {
+ val src = borders.getOrNull(xf.attrs["borderId"]?.toIntOrNull() ?: 0) ?: emptyBorder()
+ val border = XmlEl("border", LinkedHashMap(src.attrs))
+ // CT_Border is an ordered sequence: left, right, top, bottom, diagonal, vertical, horizontal.
+ fun sideEl(name: String, alt: String?, p: BorderSide?): XmlEl {
+ if (p == null) return (src.child(name) ?: alt?.let { src.child(it) }?.let { XmlEl(name, it.attrs, it.children) } ?: XmlEl(name)).copy()
+ if (p.style == null) return XmlEl(name)
+ return XmlEl(name, linkedMapOf("style" to p.style), mutableListOf(colorEl("color", p.color ?: ColorSpec(indexed = 64))))
+ }
+ border.children.add(sideEl("left", "start", patch.left))
+ border.children.add(sideEl("right", "end", patch.right))
+ border.children.add(sideEl("top", null, patch.top))
+ border.children.add(sideEl("bottom", null, patch.bottom))
+ border.children.add(src.child("diagonal")?.copy() ?: XmlEl("diagonal"))
+ src.child("vertical")?.let { border.children.add(it.copy()) }
+ src.child("horizontal")?.let { border.children.add(it.copy()) }
+ borders.add(border)
+ xf.attrs["borderId"] = (borders.size - 1).toString()
+ xf.attrs["applyBorder"] = "1"
+ }
+ if (patch.touchesAlignment) {
+ val al = xf.child("alignment")?.copy() ?: XmlEl("alignment")
+ patch.hAlign?.let { if (it == "general") al.attrs.remove("horizontal") else al.attrs["horizontal"] = it }
+ patch.vAlign?.let { if (it == "bottom") al.attrs.remove("vertical") else al.attrs["vertical"] = it }
+ patch.wrap?.let { if (it) al.attrs["wrapText"] = "1" else al.attrs.remove("wrapText") }
+ // `alignment` must precede `protection` inside an xf.
+ xf.removeChild("alignment")
+ if (al.attrs.isNotEmpty()) xf.children.add(0, al)
+ xf.attrs["applyAlignment"] = "1"
+ }
+ patch.numFmtCode?.let { code ->
+ val id = ExcelCellFormat.builtInIdFor(code)
+ ?: numFmts.entries.firstOrNull { it.value == code }?.key
+ ?: ((numFmts.keys.maxOrNull() ?: 163).coerceAtLeast(163) + 1).also { numFmts[it] = code }
+ xf.attrs["numFmtId"] = id.toString()
+ xf.attrs["applyNumberFormat"] = "1"
+ }
+ if ((xf.attrs["xfId"]?.toIntOrNull() ?: 0) >= cellStyleXfCount.coerceAtLeast(1)) xf.attrs["xfId"] = "0"
+ cellXfs.add(xf)
+ val idx = cellXfs.size - 1
+ derived[b to patch] = idx
+ return idx
+ }
+
+ private fun setFlag(font: XmlEl, n: String, on: Boolean) {
+ if (on) font.setChild(XmlEl(n)) else font.removeChild(n)
+ }
+
+ private fun colorEl(tag: String, c: ColorSpec): XmlEl {
+ val a = LinkedHashMap<String, String>()
+ when {
+ c.auto -> a["auto"] = "1"
+ c.rgb != null -> a["rgb"] = XlsxColors.hex8(c.rgb)
+ c.theme >= 0 -> a["theme"] = c.theme.toString()
+ c.indexed >= 0 -> a["indexed"] = c.indexed.toString()
+ }
+ if (c.tint != 0.0 && !c.auto) a["tint"] = c.tint.toString()
+ return XmlEl(tag, a)
+ }
+
+ private fun defaultFont() = XmlEl(
+ "font", children = mutableListOf(
+ XmlEl("sz", linkedMapOf("val" to "11")), XmlEl("color", linkedMapOf("theme" to "1")),
+ XmlEl("name", linkedMapOf("val" to "Calibri")), XmlEl("family", linkedMapOf("val" to "2")),
+ XmlEl("scheme", linkedMapOf("val" to "minor"))
+ )
+ )
+
+ private fun patternFill(type: String) = XmlEl("fill", children = mutableListOf(XmlEl("patternFill", linkedMapOf("patternType" to type))))
+ private fun emptyBorder() = XmlEl("border", children = mutableListOf(XmlEl("left"), XmlEl("right"), XmlEl("top"), XmlEl("bottom"), XmlEl("diagonal")))
+
+ companion object {
+ fun empty(theme: IntArray = XlsxColors.DefaultTheme) =
+ StyleTable(mutableListOf(), mutableListOf(), mutableListOf(), mutableListOf(), HashMap(), theme, null, 0, false)
+
+ private fun trimNum(d: Double) = if (d == Math.floor(d)) d.toLong().toString() else d.toString()
+
+ fun blend(a: Int, b: Int, t: Float): Int {
+ fun ch(x: Int, s: Int) = (x shr s) and 0xFF
+ val r = (ch(a, 16) * t + ch(b, 16) * (1 - t)).toInt()
+ val g = (ch(a, 8) * t + ch(b, 8) * (1 - t)).toInt()
+ val bl = (ch(a, 0) * t + ch(b, 0) * (1 - t)).toInt()
+ return 0xFF000000.toInt() or (r shl 16) or (g shl 8) or bl
+ }
+ }
+}
+
+internal fun String?.isTrue() = this == "1" || this == "true"
+
+/** Font properties read off a `<font>` (styles) or `<rPr>` (rich-text run) element. */
+internal class FontFacts(
+ val bold: Boolean, val italic: Boolean, val underline: Boolean, val doubleUnderline: Boolean,
+ val strike: Boolean, val size: Float, val name: String?, val argb: Int?, val vertAlign: String?
+) {
+ companion object {
+ fun of(el: XmlEl?, styles: StyleTable): FontFacts {
+ if (el == null) return FontFacts(false, false, false, false, false, 11f, null, null, null)
+ fun flag(n: String): Boolean {
+ val c = el.child(n) ?: return false
+ val v = c.attrs["val"] ?: return true
+ return v.isTrue()
+ }
+ val u = el.child("u")
+ val uVal = u?.attrs?.get("val") ?: if (u != null) "single" else "none"
+ return FontFacts(
+ bold = flag("b"), italic = flag("i"),
+ underline = uVal != "none", doubleUnderline = uVal.startsWith("double"),
+ strike = flag("strike"),
+ size = el.child("sz")?.attrs?.get("val")?.toFloatOrNull() ?: 11f,
+ name = (el.child("name") ?: el.child("rFont"))?.attrs?.get("val"),
+ argb = styles.color(el.child("color")),
+ vertAlign = el.child("vertAlign")?.attrs?.get("val")
+ )
+ }
+ }
+}